three之文字标签添加
three之文字标签添加
原理:
使用CSS2DRenderer将html标签绘制到three的画布中,放置在指定位置。
主要代码:
addLabel.js文件:(使用mixins引入主vue文件)
import * as THREE from "three"; import { CSS2DRenderer, CSS2DObject, } from "three/examples/jsm/renderers/CSS2DRenderer"; export default { data() { return { labelRenderer:new CSS2DRenderer(), labelGroup: new THREE.Group() } }, methods: { // 渲染机柜标签 addLabel(parame){ // let parame = { // position:{ // x: 176, // y:135, // z:1.7 // }, // text: "测试机柜" // } if(!(parame&¶me.position&¶me.text)){ return } this.renderLabel(parame.position,parame.text) }, // 创建标签dom renderLabel(position,text) { console.log(position) const domDiv = document.createElement( 'div' ); domDiv.className = 'label'; domDiv.textContent = text; const textLabel = new CSS2DObject( domDiv ); textLabel.position.set( position.x *15, ( position.y *1.8*2) * Math.sqrt(15)+1, position.z*15); this.labelGroup.add(textLabel) this.addLabelWrap() }, // 将标签dom添加到 addLabelWrap(){ var node = document.querySelector('.labelWrap'); if(node){ return } var labelRenderer = this.labelRenderer; labelRenderer.setSize(this.width, this.height ); labelRenderer.domElement.className = 'labelWrap'; labelRenderer.domElement.style.position = 'absolute'; labelRenderer.domElement.style.top = 0 document.querySelector('.games').appendChild(this.labelRenderer.domElement); }, // 清空标签 clearLabel(){ var node = document.querySelector('.labelWrap'); if(node){ node.remove() this.labelGroup.children = [] this.labelRenderer.domElement.innerHTML ='' } }, } }
主文件:
<div class="games" id="games"> <!-- three场景 --> <div id="container"></div> </div>
// 渲染机柜标签 this.labelGroup = new THREE.Group(); this.scene.add(this.labelGroup) // this.rackList为数据数组 [{x:0,y:0,z:0,name:"文字内容"}] this.rackList.forEach(item => { this.addLabel({position:{x:item.x,y:item.y,z:item.z},text:item.name}) })
.labelWrap { pointer-events: none; z-index: 2; } .labelWrap .label { color: #fff; font-family: sans-serif; font-size: 16px; padding: 5px 9px 14px 9px; background: url("/img/label.png") no-repeat; text-align: center; background-size: 100% 100%; }
图片文件:
钻研不易,转载请注明出处。。。。。。