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

2023-12-20 06:37:52

第一步,引入

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 = `<div>${item.label}</div>
          <div>今日电耗:1892.01kwh</div>
          `;
          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,不然容易不生效?

文章来源:https://blog.csdn.net/m0_49083276/article/details/135076791
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。