项目需求:车辆按照轨迹移动,模型上方要有文本框显示车辆信息,但是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,//被建筑物遮挡问题
},

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐