Skip to content

Instantly share code, notes, and snippets.

@ruslanchek
Created June 10, 2016 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ruslanchek/54e7d96a74205cf398eb7d789fb61efd to your computer and use it in GitHub Desktop.
Save ruslanchek/54e7d96a74205cf398eb7d789fb61efd to your computer and use it in GitHub Desktop.
TextSprite for Three.js
import * as THREE from 'three';
const FONT_FAMILY:string = 'Open Sans';
export enum TextAlign {
NONE,
START,
END,
LEFT,
CENTER,
RIGHT
}
export class TextSprite {
private canvas:HTMLCanvasElement = null;
private context:CanvasRenderingContext2D = null;
private fontWeight:number = 0;
private fontSize:number = 0;
private color:string = '#000000';
private rotation:number = 0;
private textAlign:string = '';
constructor(fontWeight:number, fontSize:number, rotation:number, color:string, textAlign:TextAlign) {
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.fontWeight = fontWeight;
this.fontSize = fontSize;
this.color = color;
this.rotation = rotation;
switch (textAlign){
case TextAlign.START : {
this.textAlign = 'start';
break;
}
case TextAlign.END : {
this.textAlign = 'end';
break;
}
case TextAlign.LEFT : {
this.textAlign = 'left';
break;
}
case TextAlign.CENTER : {
this.textAlign = 'center';
break;
}
case TextAlign.RIGHT : {
this.textAlign = 'right';
break;
}
case TextAlign.NONE : {
this.textAlign = '';
break;
}
}
}
public getTextSprite(text:string):THREE.Sprite {
this.context.font = `${this.fontWeight} ${this.fontSize}px ${FONT_FAMILY}`;
this.canvas.width = this.context.measureText(text).width;
this.canvas.height = this.fontSize * 2;
this.context.font = `${this.fontWeight} ${this.fontSize}px ${FONT_FAMILY}`;
this.context.textAlign = this.textAlign;
this.context.fillStyle = this.color;
this.context.fillText(text, 0, this.fontSize);
let texture:THREE.Texture = new THREE.Texture(this.canvas);
texture.needsUpdate = true;
texture.minFilter = THREE.LinearFilter;
let rotation = 0;
if(this.rotation !== 0){
rotation = Math.PI / (180 / this.rotation);
}
let spriteMaterial:THREE.SpriteMaterial = new THREE.SpriteMaterial({
map: texture,
rotation: rotation
});
let sprite:THREE.Sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(50, 25, 0);
return sprite;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment