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?
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With