Sprite scaling causes incorrect positioning and rotation in three.js

依然范特西╮ 提交于 2019-12-12 03:33:54

问题


I'm trying to create a sprite with text. I'm not using TextGeometry for performance reasons.

var fontsize = 18;
var borderThickness = 4;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = "Bold " + fontsize + "px Arial";
context.fillText( message, borderThickness, fontsize + borderThickness);
var texture = new THREE.Texture(canvas) 
texture.needsUpdate = true;
var spriteMaterial = new THREE.SpriteMaterial({ map: texture});
var sprite = new THREE.Sprite( spriteMaterial );

For some reason the resulting width is the half of what I expect. I tried to change the size of the canvas used to create the sprite, with weird results. So I scaled it.

sprite.scale.set(100,50,1.0);

The problem is that if I scale the image, its position and rotation is completely messed up. It seems like the width of the sprite is much larger that the width of the text. See the fiddle:

https://jsfiddle.net/ko3co15f/1/

In theory the text with "one" should be near the cube vertex, and when it rotates it should not move inside and outside the cube.

The behavior is correct in three.js revision 62:

https://jsfiddle.net/qqefadu8/4/

It seems to me a bug and I reported it to three.js github page, but it was closed.

The code is adapted from https://stemkoski.github.io/Three.js/Sprite-Text-Labels.html


回答1:


Solved. I had to change the canvas size just after canvas creation:

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');

var size = 56;
canvas.height = size;
canvas.width = size;

https://jsfiddle.net/03h4fyka/1/

Credits to WestLangley. I have another problem, I'll post it in another question.



来源:https://stackoverflow.com/questions/35386729/sprite-scaling-causes-incorrect-positioning-and-rotation-in-three-js

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