Reputation: 127
I want to colorize a png on the canvas by adding a canvas called tint which will assign the color to the png on the main canvas. But nothing is drawn at all:
js
var tint = document.createElement('canvas');
tint.width = 20;
tint.height = 20;
var tintCtx = tintCanvas.getContext('2d');
var canvas = document.getElementById('canvasA');
var ctx = canvas.getContext('2d');
var pic = new Image();
pic.src = 'http://i3.minus.com/jUyvRw7sMVxJL.png';
var x =0;
var y=0;
tintCtx.fillStyle = #ff3633;
tintCtx.fillRect(x,y,20,20);
tintCtx.globalCompositeOperation = "destination-atop";
tintCtx.drawImage(pic, x, y);
ctx.drawImage(pic, x, y);
ctx.globalAlpha = 0.5;
ctx.drawImage(tint, x, y);
Upvotes: 0
Views: 1808
Reputation:
I think I see this problem 2-3 times a week. You need to draw the image from the pic.onload event as it loads the image async - your code below pic.src executes before image is loaded.
I'm just re-arranging the code to show where you need to draw:
var tint = document.createElement('canvas');
tint.width = 20;
tint.height = 20;
var tintCtx = tintCanvas.getContext('2d');
var canvas = document.getElementById('canvasA');
var ctx = canvas.getContext('2d');
var pic = new Image();
pic.onload = function() {
tintCtx.fillStyle = #ff3633;
tintCtx.fillRect(x,y,20,20);
tintCtx.globalCompositeOperation = "destination-atop";
tintCtx.drawImage(pic, x, y);
ctx.drawImage(pic, x, y);
ctx.globalAlpha = 0.5;
ctx.drawImage(tint, x, y);
}
pic.src = 'http://i3.minus.com/jUyvRw7sMVxJL.png';
var x =0;
var y=0;
In any case you try to load an image in the fiddle that is not from the same origin so that won't work (I replaced the image url in the following fiddle so you can verify that it now draws to the canvas).
Working example:
http://jsfiddle.net/AbdiasSoftware/Br3SB/5/
Upvotes: 2