Skip to content

Instantly share code, notes, and snippets.

@kig
Created September 20, 2011 15:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kig/1229476 to your computer and use it in GitHub Desktop.
Save kig/1229476 to your computer and use it in GitHub Desktop.
Three.js canvas text
// 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;
}
@sergi
Copy link

sergi commented Jul 12, 2012

Not really working, I get TypeError: 'undefined' is not an object (evaluating 'u.x')

@kig
Copy link
Author

kig commented Jul 17, 2012

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