-
-
Save stonegao/44ea873324142ca1a98f139834ee65b8 to your computer and use it in GitHub Desktop.
TextSprite for Three.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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