THREE.js How to rotate CSS2D Text Labels

蓝咒 提交于 2021-02-08 05:34:46

问题


I am using CSS2D to display text labels as in the official example and it works OK.

Now I want to perform a one-off rotation of some of the labels in the viewing plane.

I have tried applying a CSS transform to the div before making a CSS2DObject out of the div.

But it doesnt seem to be working (the labels are still horizontal).

Here is my code (for a single label):-

var myDiv = document.createElement( 'div' );
myDiv.className = className;
myDiv.textContent = labelStr;
myDiv.style.marginTop = '-1em';
var degrees = 45;

/* *** These do not work ***

myDiv.style.webkitTransform = 'rotate('+degrees+'deg)'; 
myDiv.style.mozTransform    = 'rotate('+degrees+'deg)'; 
myDiv.style.msTransform     = 'rotate('+degrees+'deg)'; 
myDiv.style.oTransform      = 'rotate('+degrees+'deg)'; 
myDiv.style.transform       = 'rotate('+degrees+'deg)'; 
*/

var myLabel = new CSS2DObject( myDiv );             
myLabel.position.set( dX, dY, dZ ); 
//myLabel.rotateZ( degrees * Math.PI/180 ); //... *** Does not work ***

scene.add( myLabel );

I'd be grateful for any suggestions!


回答1:


If you see what it's being done by CSS2DRenderer, you´ll understand why it´s not working. Basically CSS2DRenderer is rewriting exactly those properties in the style every render loop.

    var element = object.element;
    var style = 'translate(-50%,-50%) translate(' + (vector.x * _widthHalf + _widthHalf) + 'px,' + (- vector.y * _heightHalf + _heightHalf) + 'px)';
    element.style.WebkitTransform = style;
    element.style.MozTransform = style;
    element.style.oTransform = style;
    element.style.transform = style;

So you have one option in my humble opinion, apply the transformation to a div inside the one that is managed by CSS2DRenderer. I did it in one of my projects...

See below... The one with class="label3D" is the one managed by CSS2DRenderer (equivalent to your myDiv), and its children is the one that I create explicitly to apply the transformation. The result in the html would be like this...

    <div class="label3D" style="position: absolute; transform: translate(-50%, -50%) translate(487.583px, 205.32px); z-index: 36;">
        <div style="transform: rotate(45deg)">
            <i class="fas fa-exclamation-triangle text-yellow" title="NOCOMPLIANT"></i>
        </div>
    </div>

So in your code, you only need to append a new children div to your myDiv and apply the transformation to the children instead of to myDiv, and then it will be "respected" by CSS2DRenderer.



来源:https://stackoverflow.com/questions/64839541/three-js-how-to-rotate-css2d-text-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!