Offline
Online
Viewers

Drawing on Textures in ThreeJS

If you’re an avid user of ThreeJS you have more than likely at some point run into the situation where you need to either create a texture from scratch for the point of coloring it, or have had the need to update/draw on a texture for one reason or another.  The following will walk you through what is needed to accomplish this.

First, start by creating an in memory canvas object that we will use to draw on.  This will eventually be transformed into a texture object.

[codesyntax lang=”javascript”]

//create in memory canvas
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext("2d");

[/codesyntax]

 

For this example, I’m creating a simple 100×100 pixel image and retrieving the 2d context which we will next use for performing that actual modification of the image.

[codesyntax lang=”javascript”]

//paint the image red
context.fillStyle = "#ff0000";
context.fillRect(0, 0, 100, 100);

[/codesyntax]

 

Here we’re setting the fill color to red and painting the entire image.  Next, let’s convert our in memory canvas object into an image.

[codesyntax lang=”javascript”]

//create image from canvas
var image = new Image();
image.src = canvas.toDataURL();

[/codesyntax]

 

Finally, let’s take our new image and create a texture object which can be applied to a material.

[codesyntax lang=”javascript”]

//create new texture
var texture = new THREE.Texture(image);
texture.anisotropy = 4;
texture.needsUpdate = true;

//apply texture to a material, go forth and be merry

[/codesyntax]

 

That’s really all there is to it, you can make the context draw lines, rects, etc. onto the in memory canvas until your heart’s content.  For convenience, the following is the entire code example wrapped up into one.

[codesyntax lang=”javascript”]

//create in memory canvas
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext("2d");

//paint the image red
context.fillStyle = "#ff0000";
context.fillRect(0, 0, 100, 100);

//create image from canvas
var image = new Image();
image.src = canvas.toDataURL();

//create new texture
var texture = new THREE.Texture(image);
texture.anisotropy = 4;
texture.needsUpdate = true;

//apply texture to a material, go forth and be merry

[/codesyntax]

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Affiliates