meta-next
Version:
76 lines (60 loc) • 1.55 kB
JavaScript
import RenderNode from "./RenderNode"
import Texture from "../resources/Texture"
class Text extends RenderNode
{
constructor(text)
{
super()
this.canvas = document.createElement("canvas")
this.ctx = this.canvas.getContext("2d")
this.texture = new Texture()
this._text = ""
this._font = "Arial"
this._fontSize = 30
this._fontWeight = 200
if(text) {
this.text = text
}
}
updateMesh()
{
const fontStyle = `${this._fontWeight} ${this._fontSize}px ${this._font}`
this.ctx.font = fontStyle
const metrics = this.ctx.measureText(this._text)
this.canvas.width = metrics.width + 4
this.canvas.height = this._fontSize * 1.7
this.size.set(this.canvas.width, this.canvas.height)
this.ctx.font = fontStyle
this.ctx.fillStyle = "#ffffff"
this.ctx.textBaseline = "top"
this.ctx.fillText(this._text, 2, -1)
this.texture.loadFromCanvas(this.canvas)
this.needUpdateTransform = true
document.body.appendChild(this.canvas)
}
set text(text) {
if(this._text === text) { return }
this._text = text
this.needUpdateOffset = true
}
get text() {
return this._text
}
set font(font) {
if(this._font === font) { return }
this._font = font
this.needUpdateOffset = true
}
get font() {
return this._fontSize
}
set fontSize(fontSize) {
if(this._fontSize === fontSize) { return }
this._fontSize = fontSize
this.needUpdateOffset = true
}
get fontSize() {
return this._fontSize
}
}
export default Text