https://blog.csdn.net/tutouxiaoyaonie/article/details/127306197
项目需求:车辆按照轨迹移动,模型上方要有文本框显示车辆信息,但是cesium自带的label设置样式有限,不美观,所以采取canvas生成图片,用billboard加载的方法实现。
cesium官网例子,label样式:
处理后样式,可修改字体,边距等数据
代码如下:
(1)封装的js
let showLabelFun = (dataMcInfo) => {
var c = document.createElement("canvas");
var settings = {
canvas:c,
canvasWidth:150, //canvas的宽度
canvasHeight:65, //canvas的高度
drawStartX:15, //绘制字符串起始x坐标 距离左侧
drawStartY:28, //绘制字符串起始y坐标 距离顶部
font:"12px 'Microsoft Yahei'", //文字样式
text:"请修改掉默认的配置", //需要绘制的文本
color:"#ffffff",//"#000000", //文字的颜色
backgroundColor:"rgba(38, 38, 38, 0.75)"//"#ffffff"//背景颜色
};
//绘制带有圆角的背景
CanvasRenderingContext2D.prototype.roundRect =
function (x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined") {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
this.beginPath();
this.moveTo(x + radius, y);
this.lineTo(x + width - radius, y);
this.quadraticCurveTo(x + width, y, x + width, y + radius);
this.lineTo(x + width, y + height - radius);
this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
this.lineTo(x + radius, y + height);
this.quadraticCurveTo(x, y + height, x, y + height - radius);
this.lineTo(x, y + radius);
this.quadraticCurveTo(x, y, x + radius, y);
this.fillStyle = settings.backgroundColor;
this.closePath();
if (stroke) {
this.stroke();
}
if (fill) {
this.fill();
}
};
//获取2d的上线文开始设置相关属性
var canvas = settings.canvas;
canvas.width = settings.canvasWidth;
canvas.height = settings.canvasHeight;
var ctx = canvas.getContext("2d");
//绘制带有圆角的背景
ctx.roundRect(0,0,canvas.width,canvas.height,15,true)
//填充文字
ctx.font = settings.font;
ctx.fillStyle = settings.color;
ctx.fillText('终端名称:自动驾驶车01',settings.drawStartX,settings.drawStartY);
ctx.fillText('速度:30 km/h',settings.drawStartX,settings.drawStartY+20);
return canvas.toDataURL();
//下载图片测试查看
//var src = canvas.toDataURL();
// var a = document.createElement('a');
// var event = new MouseEvent('click');
// a.download = (new Date()).getTime() + ".jpg"; // 指定下载图片的名称
// a.href = src;
// a.dispatchEvent(event); // 触发超链接的点击事件
}
(2)引用
billboard: {
image: showLabelFun(''),
pixelOffset: new Cesium.Cartesian2(0, -50),
disableDepthTestDistance: Number.POSITIVE_INFINITY,//被建筑物遮挡问题
},
本文转自 https://blog.csdn.net/tutouxiaoyaonie/article/details/127306197,如有侵权,请联系删除。
标签:canvas,自定义,settings,height,width,radius,var,label From: https://www.cnblogs.com/hustshu/p/17150740.html