基于vue与three.js给模型添加标签(CSS2DRenderer与CSS2DObject)

基于vue与three.js给模型添加标签(CSS2DRenderer与CSS2DObject)_第1张图片

第一步,引入

import {
  CSS2DRenderer,
  CSS2DObject,
} from "three/examples/jsm/renderers/CSS2DRenderer.js";

第二步,创建渲染器

this.tagRenderer = new CSS2DRenderer();
      this.tagRenderer.setSize(this.w, this.h);
      this.tagRenderer.domElement.style.position = "absolute";
      this.tagRenderer.domElement.style.zIndex = 9999999;
      this.tagRenderer.domElement.style.top = "0px";
      this.tagRenderer.domElement.style.pointerEvents = "none";
      this.$refs.three_container.appendChild(this.tagRenderer.domElement);

this.$refs.three_container为3D渲染的容器,注意zindex必须足够高

animate方法:

 animate() {
      if (!this.renderer) {
        return;
      }
      requestAnimationFrame(this.animate);
      this.controls.update(); // 更新控制器状态
      TWEEN.update();
      this.renderer.render(this.scene, this.camera);
      if (!this.tagRenderer) {
        return;
      }
      this.tagRenderer.render(this.scene, this.camera);
    },

第三步,创建dom

 this.options.forEach((item) => {
        if (item.position) {
          let domEle = document.createElement("div");
          domEle.className = "tag";
          domEle.innerHTML = `
${item.label}
今日电耗:1892.01kwh
`; let domEleObj = new CSS2DObject(domEle); domEleObj.position.set( item.position.x, item.position.y, item.position.z ); this.scene.add(domEleObj); } });
::v-deep .tag {
  box-shadow: 0 0 2px #00ffff inset;
  background: linear-gradient(#00ffff, #00ffff) left top;
  background-repeat: no-repeat;
  background-size: 1px 6px, 6px 1px;
  background-color: rgba(0, 0, 0, 0.8);
  color: #ffffff;
  font-size: 12px;
  padding: 4px 10px;
  position: absolute;
  z-index: 9;
  display: inline;

}

得用deep,不然容易不生效 

你可能感兴趣的:(vue,与,three,javascript,vue.js,前端)