jawns317
jawns317

Reputation: 1746

HTML5 canvas: Toggle between color/grayscale image

I've got an HTML5 canvas element in which a user can dynamically move, resize, and rotate a color photo.

I'd like the user to be able to toggle between grayscale and color.

I can think of two approaches, but neither is ideal:

1) Re-render the color image as grayscale (using a pixel-by-pixel loop) on every resize and rotate event (which could be several times a second)

2) Create a grayscale version server-side, and apply any canvas transformations to both images, but show only one of them at a time, depending on the toggle selection.

Can anyone think of a better solution than these two -- or, if no better solution exists, take a guess about which of the two would be the better choice?

Update: I implemented the method suggested below by Phrogz.

Upvotes: 2

Views: 1918

Answers (2)

Phrogz
Phrogz

Reputation: 303198

Create a second canvas (you don't even have to append it to the document) and use drawImage() to copy the color image onto it, and then (once) use getImageData()/putImageData() to make it greyscale.

Use this canvas as the source for future calls to drawImage() when you need the greyscale version, otherwise use the original image.

You are transforming the context, e.g. context.translate() / context.rotate() / context.scale(), to draw the image easily, right? There is no reason to keep rotating or resizing the source image as the user is transforming it.

Upvotes: 1

Dykam
Dykam

Reputation: 10290

You can also draw both images to two canvases (or a big one). That canvas probably doesn't even have to be added to the page, it can just be the element.

Then you draw the proper image from that canvas to the main canvas using the build-in methods. This will both be fast and not require server-side code.

You could even do the conversion to grayscale in a webworker, but that depends on if your clients do support it.

Upvotes: 0

Related Questions