2013-06-01 96 views
0

我想通過添加一個名爲tint的畫布給畫布上的png着色,該畫布將顏色分配給主畫布上的png。但沒有什麼是繪製在所有:在畫布上着色png

js fiddel code

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); 

回答

2

我想我看到這個問題,每週2-3次。您需要從pic.onload事件中繪製圖像,因爲它會加載圖像異步 - 在加載圖像之前,您的代碼在pic.src下執行。

我只是重新編排的代碼來顯示你需要畫:

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; 

在任何情況下,你嘗試加載不是來自同一來源,從而贏得了小提琴的圖像不工作(我在下面的小提琴中替換了圖像url,以便您可以驗證它現在繪製到畫布上)。

工作例如:
http://jsfiddle.net/AbdiasSoftware/Br3SB/5/