Is there a three.js version of html drawImage and getImage?

Is there something in three.js that is similar to the html drawImage and getImage routines?

I use these to combine and split images in my main program, but am not sure that I could use them in a separate module. Also, it seems that it would be nice to be consistent not mix html routines with three.js routines.

You mean the canvas’s 2D context, drawImage, and getImageData. You can use the canvas directly with a CanvasTexture and set needsUpdate after each new drawing. This should also work with OffscreenCanvas.

1 Like

Yes, the 2D context. I currently use it offscreen to initialize images which then I turn into textures and then materials.

I currently initialize the canvas and context with this:

let canvas = document.createElement("canvas");
	canvas.width = 1024;
	canvas.height = 1024;
let context = canvas.getContext('2d',{willReadFrequently: true});

So if I pass the canvas and context values to separate modules, the modules can use the drawImage and getImageData html subroutines?

1 Like

Yes, something like the following would work, and it’s always a good practice to use modules while following the DRY (Don’t Repeat Yourself) principle.

// Main.js
import { drawImageOnCanvas, extractImageData } from './canvasUtils.js';

const canvas = document.createElement('canvas');
canvas.width = 1024;
canvas.height = 1024;
const context = canvas.getContext('2d', { willReadFrequently: true });

const image = new Image();
image.src = 'example.jpg';
image.onload = () => {
   drawImageOnCanvas(context, image, 0, 0, 1024, 1024);

   const imageData = extractImageData(context, 0, 0, 1024, 1024);
   console.log('Extracted image data:', imageData);
};
// canvasUtils.js
export function drawImageOnCanvas(context, image, x, y, width, height) {
    context.drawImage(image, x, y, width, height);
}

export function extractImageData(context, x, y, width, height) {
    return context.getImageData(x, y, width, height);
}
1 Like