richie
richie

Reputation: 2478

Use drawImage to draw pixel data on canvas

I have a pixel-array and I would like to draw it onto the canvas, without using the putImageData, because that function ignores clip data.

So, just to make this work i've converted the pixel-array to a data-url, and then appended the url to an image which I then draw onto the canvas, like this:

var ctx = {
    display: document.querySelector('canvas#display').getContext('2d'),
    convert: document.querySelector('canvas#convert').getContext('2d')
}

var image_data = THE_IMAGE_DATA_THAT_I_ALREADY_HAVE;

ctx.convert.putImageData(image_data, 0, 0);

var image_data_URL = ctx.convert.canvas.toDataURL('image/png');
var converter_image = document.querySelector('img#converter-image');

converter_image.onload = function () {
    ctx.display.save();
    ctx.display.beginPath();
    ctx.display.arc(320, 240, 240, 0, Math.PI*2, true);
    ctx.display.clip();
    ctx.display.drawImage(converter_image, 0, 0, 640, 480);
    ctx.display.restore();
}
converter_image.src = image_data_URL;

However, this is gives a REALLY bad performance, especially since I want to do this 60/sec.

There must be another way, right?

Upvotes: 0

Views: 1758

Answers (1)

Pierre
Pierre

Reputation: 1282

A work around will be to draw your pixel using getImageData / putImageData in an offscreen canvas then drawing the offscreen canvas back in your canvas.

More infos :

Canvas offscreen

Pixel drawing with putImagedata (click on the blank in top of the code to launch it)

Upvotes: 2

Related Questions