Introduction
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.
Getting Started
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.
//create in memory canvas
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext("2d");
Creating The Context
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.
//paint the image red
context.fillStyle = "#ff0000";
context.fillRect(0, 0, 100, 100);
Creating The Image
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.
//create image from canvas
var image = new Image();
image.src = canvas.toDataURL();
Creating The Texture
Finally, let’s take our new image and create a texture object which can be applied to a material.
//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
All Together Now
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.
//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
0 Comments