Created
September 20, 2011 15:52
-
-
Save kig/1229476 to your computer and use it in GitHub Desktop.
Three.js canvas text
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
// Usage: | |
// var txt = alignPlane(createText2D('String', 'red', 'Verdana', 64), THREE.RightAlign, THREE.BottomAlign); | |
// scene.addChild(txt); | |
function createTextCanvas(text, color, font, size) { | |
size = size || 24; | |
var canvas = document.createElement('canvas'); | |
var ctx = canvas.getContext('2d'); | |
var fontStr = (font || 'Arial') + ' ' + (size +'px'); | |
ctx.font = fontStr; | |
var w = ctx.measureText(text).width; | |
var h = Math.ceil(size*1.25); | |
canvas.width = w; | |
canvas.height = h; | |
ctx.font = fontStr; | |
ctx.fillStyle = color || 'black'; | |
ctx.fillText(text, 0, size); | |
return canvas; | |
} | |
function createText2D(text, color, font, size, segW, segH) { | |
var canvas = createTextCanvas(text, color, font, size); | |
var plane = new THREE.PlaneGeometry(canvas.width, canvas.height, segW, segH); | |
var tex = new THREE.Texture(canvas); | |
tex.needsUpdate = true; | |
var planeMat = new THREE.MeshBasicMaterial({ | |
map: tex, color: 0xffffff, transparent: true | |
}); | |
var mesh = new THREE.Mesh(plane, planeMat); | |
mesh.doubleSided = true; | |
return mesh; | |
} | |
THREE.LeftAlign = 1; | |
THREE.CenterAlign = 0; | |
THREE.RightAlign = -1; | |
THREE.TopAlign = -1; | |
THREE.BottomAlign = 1; | |
function alignPlane(plane, horizontalAlign, verticalAlign) { | |
var obj = new THREE.Object3D(); | |
var u = plane.geometry.vertices[0].position; | |
var v = plane.geometry.vertices[plane.geometry.vertices.length-1].position; | |
var width = Math.abs(u.x - v.x); | |
var height = Math.abs(u.y - v.y); | |
plane.position.x = width/2 * horizontalAlign; | |
plane.position.y = height/2 * verticalAlign; | |
obj.addChild(plane); | |
return obj; | |
} | |
Three.js API changed, I think you need to do var u = plane.geometry.vertices[0]; etc.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not really working, I get
TypeError: 'undefined' is not an object (evaluating 'u.x')