I noticed a strange problem with getImageData
; transparency of the image seems to be ignored when the image data is fetched.
Since any image needs to be drawn on to a canvas
before its image data can be obtained, I assumed this was a problem with the canvas
in question being opaque. But I was wrong, since using the canvas
as an argument in drawImage
maintains transparency.
Here is how I loaded the image;
var load_image = function(name, url, holder, callback) {
var img = new Image();
img.src = url;
img.addEventListener('load', function(e) {
var canvas = make_canvas(e.target.width, e.target.height);
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(e.target, 0, 0);
holder[name] = {canvas: canvas, ctx: ctx};
delete e.target;
callback.call();
}, false);
};
The callback
is simply the draw function, which invokes draw_image
to draw the image.
The usual version;
var draw_image = function(ctx, img, sx, sy, w, h, dx, dy) {
ctx.drawImage(img.canvas, sx, sy, w, h, dx, dy, w, h);
};
It simply takes the canvas as an argument for drawImage
, and the result is as intended with transparency maintained. Example.
The image data version;
var draw_image = function(ctx, img, sx, sy, w, h, dx, dy) {
var imagedata = img.ctx.getImageData(sx, sy, w, h);
ctx.putImageData(imagedata, dx, dy);
};
This one obtains the image data of the required rectangle from the same canvas as the one used in the usual version, and puts the image data on the canvas I want to draw to. I believe transparency should be maintained, but this is not so. Example. (This is a Dropbox link because of the origin-clean
flag.)
Am I wrong in assuming that transparency should be maintained with getImageData
? Or am I just using it in a wrong manner?
Either way, help would really be appreciated.