I’m having a problem with sprite scaling - I get really inconsistent results for the sprite size.
I’m using sprites to put nameplates above the character’s heads. I create a canvas element, CanvasTexture, SpriteMaterial, and Sprite, and then use measureText to determine how big the canvas needs to be to contain the character’s name:
let ctx = this.canvas.getContext('2d')!;
ctx.font = NAMEPLATE_FONT;
const textSize = ctx.measureText(name);
const width = Math.max(
GAUGE_WIDTH + 4,
Math.ceil(textSize.width) + NAMEPLATE_OUTLINE_WIDTH * 2
);
const height = Math.ceil(
textSize.actualBoundingBoxAscent +
textSize.actualBoundingBoxDescent +
GAUGE_HEIGHT +
GAUGE_TOP_MARGIN +
NAMEPLATE_OUTLINE_WIDTH * 2
);
this.canvas.width = width;
this.canvas.height = height;
Then I create a new drawing context and render the text into the canvas:
const x = Math.round((width - textSize.width) * 0.5);
const y = textSize.actualBoundingBoxAscent + NAMEPLATE_OUTLINE_WIDTH;
if (showName) {
ctx.font = NAMEPLATE_FONT;
ctx.lineWidth = NAMEPLATE_OUTLINE_WIDTH * 2;
ctx.strokeStyle = '#000';
ctx.strokeText(name, x, y);
ctx.fillStyle = '#fff';
ctx.fillText(name, x, y);
}
Finally, I set the scale of the sprite based on the aspect ratio of the canvas:
this.sprite.scale.set((width / height) * 0.05, 0.05, 1);
this.sprite.center.set(0.5, 0);
this.sprite.visible = true;
However, what I am seeing is:
- Sometimes the sprites look correct.
- Sometimes they are way too small.
- Sometimes they are stretched or squashed (incorrect aspect ratio).
- Sometimes they are not centered properly above the character’s heads (offset horizontally).
Note that in some cases, even just doing a page refresh - without changing any code - will cause the sprite to look different. I’ve also seen cases where two characters are standing next to each other, and one has a tiny nameplate while the other has a normal-sized nameplate.