Reputation: 16726
I have a complex image drawn onto a canvas, and I want to be able to arbitrarily change transparency of areas within that image. I got those areas outlined as masks in separate files. Is there a way to accomplish this?
What I was thinking was to analyze canvas pixel by pixel and if the pixel under question falls into specific area outlined by a mask, modify it's transparency accordingly. But then I'm not sure how to check if pixel is within the area? I could probably have a separate canvas element for each area and merely check if corresponding pixel is there or not. But it sounds clunky. Any better way? Elegant? Maybe some math magic? Or a method that I'm not aware of?
Upvotes: 2
Views: 623
Reputation: 382150
If you want to check whether a pixel is black or white in an image, you first need to get the data using getImageData and then you simply have to check the value (4 bytes because RGBA) at the correct coordinates.
var maskCanvas = document.createElement('canvas');
maskCanvas.width = w;
maskCanvas.height = h;
var context = maskCanvas.getContext('2d');
context.drawImage(yourMaskImage, 0, 0);
var pixels = context.getImageData(0, 0, w, h).data;
If your image has dimensions (w, h)
, your array will have a size of w*h*4
and you'll be able to get a color at (x,y)
using this :
var i = 4*(x+w*y); //
var color = (pixels[i]<<16) + (pixels[i+1]<<8) + (pixels[i+2]); // I don't care about the alpha
As you work directly on a byte array, this is very fast (if you keep the array between checks).
Be aware that the image containing the mask must come from the same domain as your main page.
Upvotes: 3