CanvasBillboard.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //通过Canvas绘制复杂或动态对象的图标点Graphic
  2. class CanvasBillboard extends mars3d.graphic.BillboardEntity {
  3. /**
  4. * 文字
  5. * @type {string}
  6. */
  7. get text() {
  8. return this.style.text;
  9. }
  10. set text(val) {
  11. this.style.text = val;
  12. this._updateCanvas();
  13. }
  14. /**
  15. * 对象添加到图层前创建一些对象的钩子方法,
  16. * 只会调用一次
  17. * @return {void} 无
  18. * @private
  19. */
  20. _mountedHook() {
  21. super._mountedHook();
  22. //图片对象
  23. this.style.imageUrl = "img/marker/textPnl.png";
  24. this.style.width = 300;
  25. this.style.height = 140;
  26. if (!this._canvas) {
  27. this._canvas = document.createElement("canvas");
  28. this._canvas.width = this.style.width;
  29. this._canvas.height = this.style.height;
  30. }
  31. if (!this._pngImage) {
  32. let img = new Image(this.style.width, this.style.height);
  33. img.crossOrigin = "Anonymous";
  34. img.src = this.style.imageUrl;
  35. img.onload = () => {
  36. this._pngImage = img;
  37. this._updateCanvas();
  38. };
  39. }
  40. this._updateCanvas();
  41. }
  42. //创建canvas
  43. _updateCanvas() {
  44. if (!this._pngImage || !this._canvas) {
  45. return;
  46. }
  47. let canvas = this._canvas;
  48. let ctx = canvas.getContext("2d");
  49. ctx.clearRect(0, 0, canvas.width, canvas.height);
  50. //绘制图片
  51. ctx.drawImage(this._pngImage, 0, 0);
  52. //绘制文字
  53. ctx.fillStyle = "rgb(255, 255, 255)";
  54. ctx.font = "55px 楷体";
  55. ctx.textBaseline = "middle";
  56. ctx.fillText("温度:", 20, canvas.height / 2);
  57. ctx.fillText(this.style.text, 160, canvas.height / 2);
  58. ctx.fillText("℃", 220, canvas.height / 2);
  59. let newImg = new Image(canvas.width, canvas.height);
  60. newImg.src = canvas.toDataURL("image/png");
  61. //将图片赋予给矢量对象进行显示,this.image是父类的属性
  62. this.image = newImg;
  63. }
  64. }
  65. mars3d.graphic.CanvasBillboard = CanvasBillboard;