Marco Sulla
Marco Sulla

Reputation: 15930

Sprite scaling causes incorrect positioning and rotation in three.js

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

Upvotes: 0

Views: 845

Answers (1)

Marco Sulla
Marco Sulla

Reputation: 15930

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.

Upvotes: 1

Related Questions