文字 https://www.cnblogs.com/chencarl/p/11725091.html
https://blog.csdn.net/towrabbit/article/details/80028485
缩放时文字大小不变:
https://stackoverflow.com/questions/40446915/three-js-keep-label-size-on-zoom/40452050#40452050
Canvas绘制的文字模糊的问题 经测试,发现不能设置高度,且宽度也不能设置,否则会被拉伸
另外距离镜头的远近,也有影响,距离近了,会被拉伸,针对镜头远近导致的拉伸,可以通过计算scale来处理:
I figure you could calculate the distance from each label to the camera then come up with some sort of scaling factor based on that.
And it’s very simple. Let’s say, a THREE.Sprite() object (label) is a child of a THREE.Mesh() object (planet), then in your animation loop you need to do.
1 2 3 4 5 6 var scaleVector = new THREE .Vector3 ();var scaleFactor = 4 ;var sprite = planet.children [0 ];var scale = scaleVector.subVectors (planet.position , camera.position ).length () / scaleFactor; sprite.scale .set (scale, scale, 1 );
通过DIV绘制文字 注意div绘制的文字,设置位置的时候,不要通过position去设置,否则会因为三维坐标和二维坐标的差异,导致在缩放后位置不准确。
正确的定位方式,是:
1、先给文本对象设置其依赖的对象的三维坐标:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 const div = document .createElement ('div' ); div.innerHTML = text; div.style .color = option.color ; div.style .fontSize = `${option.fontSize} px` ; div.style .position = 'absolute' ; const label = new CSS2DObject (div); label.position .set ( position[0 ], position[1 ], position[2 ], );
2、通过CSS样式设置偏移量:
1 2 const left = position[0 ] > 0 ? labelWidth / 2 + option.borderWidth : labelWidth / -2 - option.borderWidth ; div.style .left = `${left} px` ;
完整的绘制示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer' ;const getTextByDiv = (text, opt, position ) => { const option = { fontFamily : (opt.label && opt.label .fontFamily ) || 'Microsoft Yahei' , fontSize : (opt.label && opt.label .fontSize ) || 10 , fontWeight : (opt.label && opt.label .fontWeight ) || 'bold' , lineHeight : 1.4 , color : (opt.label && opt.label .color ) || 'rgba(0,0,0,0.60)' , borderWidth : 4 , borderRadius : 6 , borderColor : 'transparent' , backgroundColor : '' , }; const div = document .createElement ('div' ); div.innerHTML = text; div.style .padding = '5px 10px' ; div.style .color = option.color ; div.style .opacity = opt.opacity ; div.style .fontSize = `${option.fontSize} px` ; div.style .fontWeight = option.fontWeight ; div.style .position = 'absolute' ; div.style .backgroundColor = option.backgroundColor ; div.style .borderRadius = option.borderRadius ; const label = new CSS2DObject (div); const labelWidth = metureTextWidth (text, option) + option.borderWidth * 2 ; console .log (labelWidth); const left = position[0 ] > 0 ? labelWidth / 2 + option.borderWidth : labelWidth / -2 - option.borderWidth ; div.style .left = `${left} px` ; label.position .set ( position[0 ], position[1 ], position[2 ], ); return label; };