Frank Conway
Frank Conway

Reputation: 23

Change colour of image with HTML 5 canvas tag and jquery

Here is a Fiddle

The image is a orange square with a transparent circle. Is there anyway to change the colour of the the orange without effecting the transparent circle/background with html 5 canvas tag + jquery. If there is a better method I would like to hear that too.

Upvotes: 0

Views: 1441

Answers (1)

Basically you want to do something that can be achieved with most image editing softwares. Canvas can be very powerful if you write scripts to manipulate it. For instance, when using CanvasContext (obtained through the getContext("2d") on the canvas element) you can get and put image data, which is basically a collection of pixels represented by 4 bytes each (RGBA). That means that you end up with an array of length Width * Height * 4.

Now i'm no expert on image/canvas manipulation, so what I suggest can probably be done far more easly. If you want to change the orange part of the image, like say paint an image over it (or a plain color), on any image editing software that would mean that you need to use a mask. As far as I know, here, to use a mask you would have to:

  1. Your image should be drawn on a canvas element to manipulate it.
  2. Create a secondary workspace canvas.
  3. Draw your brush (the image you want to paint) onto the workspace.
  4. Get the workspace canvas imageData.
  5. Replace the Alpha channel of the obtained ImageData (with the one from the image of the original canvas)
  6. Clear the workspace canvas.
  7. Put the new image data onto the workspace canvas.
  8. Draw the workspace canvas onto the original canvas.

That would mean that your brush (plain color) would have an applied Alpha channel that has the exact same shape as the orange part of the original image.

Now, at least on chrome, there is a problem with that image from imageshack, and that is that you cannot obtain the imageData of a canvas elemen drawn with an image from an external domain. Doing so woul result on an exception saying that the canvas was tainted with data from other domains. That means that the image you want to manipulate should be hosted under the same domain that your test site is run of. (You must check canvas documentation to see how to avoid that).

Please note that this aims to something more powerful thant just changing the shape color. If you just want to change it's color you can just manipulate the original canvas' imageData RGB channels until you find your desired color.

Some useful links:

Upvotes: 1

Related Questions