saward
saward

Reputation: 439

Speeding up pixel manipulation in html5 canvas

I am having some slowness with some image filtering I'm trying to do. I can fix the problem I'm having by simply caching the changes I make. However, I'd like to optimise this as much as I can without caching first, before I implement that. Basically, it's slow, because I'm modifying multiple separate images of about 64x64 pixels each redraw. As I said, caching will fix this, but I want to optimise other ways first.

These are the two ideas I've had:

1.Reduce copying of image

I already have the image I want to modify, stored in an image, as a part of it. In other words, I have a sprite sheet loaded into memory, and so there is a portion of the image I want to modify for a new draw. Is there a way to grab imageData directly from the image, rather than having to draw the image to a new canvas first, then get the imageData from that? It seems inefficient to have to copy the image to a canvas, and then obtain the pixel data via getImageData.

2.Use drawImage instead of putImageData

drawImage seems to be much faster than putImageData. But I can't find any way to draw my modified pixel data to a canvas through drawImage and avoiding putImageData altogether. Is there a way?

Thanks

Upvotes: 1

Views: 330

Answers (1)

Jani Hartikainen
Jani Hartikainen

Reputation: 43273

1: No. You need to draw the image on a canvas in order to obtain the imagedata.

2: You can't draw imagedata using anything else than putImageData. As you say, caching it into a new canvas or an Image is the solution for this. You can draw another canvas using drawImage just like you can draw an Image.

Upvotes: 1

Related Questions