ThreeJS render text in canvas as texture and then apply to a plane?

12,082

This is a simple code to add text from a canvas as a texture:

//create image
var bitmap = document.createElement('canvas');
var g = bitmap.getContext('2d');
bitmap.width = 100;
bitmap.height = 100;
g.font = 'Bold 20px Arial';

g.fillStyle = 'white';
g.fillText(text, 0, 20);
g.strokeStyle = 'black';
g.strokeText(text, 0, 20);

// canvas contents will be used for a texture
var texture = new THREE.Texture(bitmap) 
texture.needsUpdate = true;

it needs some work... like setting the output text size to the canvas' size.

Share:
12,082
jctjct3
Author by

jctjct3

I spend much of my free time making games and trying to learn new concepts.

Updated on June 09, 2022

Comments

  • jctjct3
    jctjct3 almost 2 years

    I've been looking all day for a way to procedurally generate 2d texture with text in them so that I can apply them as a texture to a plane. Basically, I want to be able to change what text shows up in my WebGL page without having to just use texture made in an image editing program. I'm aiming to be able to edit the content of the page just as easily as with a totally 2d page, just edit the code and bam, it's there.

    The most promising method I've seen to accomplish this is to render the text in a blank canvas with CSS, use that canvas as a texture which ThreeJS makes very easy, and then apply that texture to a plane that I can place wherever in the 3d environment. I've attempted to accomplish this by adapting this example to my needs: http://jsfiddle.net/sSD65/28/

    However, I end up with a totally black page, indicating an error somewhere. An error that I cannot, for the life of me, find and fix. I have a feeling I'm missing something because of my lack of experience with ThreeJS and in fact Javascript in general so I've come here to ask for your help.

    I really appreciate any help I can get here. Here's a link to the page, although I don't think you will be able to view it properly without hosting it locally since I'm loading an image from a folder there, but Python is wonderful for that. Just use Python -m SimpleHTTPServer in the console once you've navigated to that folder and it will host it locally so that you can access it from "http://localhost:8000/homepage.html": https://dl.dropbox.com/u/40043006/WebGLTest.zip