Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way of blitting part of offscreen canvas to an onscreen canvas

Tags:

html

canvas

I want to write a blit part of an offscreen canvas (ie coords x,y and width height w,h) to an onscreen canvas. Can this be done and what is the fastest way of doing this?

like image 916
Rewind Avatar asked Feb 22 '23 23:02

Rewind


1 Answers

Yes, you just need to use drawImage() or putImageData(). The drawImage() function call can take a canvas as a data source parameter, so you can draw to your on-screen canvas using the off-screen one as the source. If you have transparency that you need to maintain, you will need to use putImageData() which does a complete overwrite of the existing canvas data. Conversely, drawImage() will apply a blending mode to the data using the globalCompositeOperation parameter of your context.

var offscreen_canvas = document.getElementById("offscreen_canvas");
var onscreen_canvas = document.getElementById("onscreen_canvas");
var onscreen_context = onscreen_canvas.getContext("2d");

// Don't care about transparency:
onscreen_context.drawImage(offscreen_canvas, source_x, source_y, source_width, source_height, dest_x, dest_y, dest_width, dest_height);

// Or, if we care about transparency preservation:
var offscreen_context = offscreen_canvas.getContext("2d");
var offscreen_data = offscreen_context.getImageData(x, y, width, height);

onscreen_context.putImageData(offscreen_data, dest_x, dest_y);

References: drawImage() and putImageData().

like image 100
Xenethyl Avatar answered May 02 '23 00:05

Xenethyl