2016-09-19 76 views
0

我想反轉圖像的顏色。現在圖像加載好了,但是當我嘗試調用getImageData和putImageData回到畫布上。畫布簡直是空白。然後我打印出所有的imageData,由於某種原因,它看起來總是0。我對此感到非常困擾。請提前幫助和thx!畫布獲取圖像數據返回0始終

window.onload = function() { 
    var c = document.getElementById("myCanvas"); 
    var ctx = c.getContext("2d"); 
    var img = new Image(); 
    img.src = "hand.jpg"; 
    img.onload = function() { 
     ctx.drawImage(img, 10, 10,50,50); 
    } 

    var imgData = ctx.getImageData(10,10,50,50); 
    console.log(imgData.data.toString()); //return 0's 
    for (var i=0;i<imgData.data.length;i+=4) 
    { 
     imgData.data[i]=255-imgData.data[i]; 
     imgData.data[i+1]=255-imgData.data[i+1]; 
     imgData.data[i+2]=255-imgData.data[i+2]; 
     imgData.data[i+3]=255; 
    } 
    ctx.putImageData(imgData,100,100); 
} 

回答

2

你需要等待圖像加載

window.onload = function() { 
    var c = document.getElementById("myCanvas"); 
    var ctx = c.getContext("2d"); 
    var img = new Image(); 
    img.src = "hand.jpg"; 
    //================================================================ 
    // this event will only get called after you have returned from this function 
    img.onload = function() { 
     ctx.drawImage(img, 10, 10,50,50); 
    } 
    //================================================================ 
    // The image has not loaded at this point 
    // the following code will always be working on an empty canvas 

    var imgData = ctx.getImageData(10,10,50,50); 
    console.log(imgData.data.toString()); //return 0's 
    for (var i=0;i<imgData.data.length;i+=4) 
    { 
     imgData.data[i]=255-imgData.data[i]; 
     imgData.data[i+1]=255-imgData.data[i+1]; 
     imgData.data[i+2]=255-imgData.data[i+2]; 
     imgData.data[i+3]=255; 
    } 
    ctx.putImageData(imgData,100,100); 

    //================================================================ 
    // onload will fire after this point 
} 

要解決

window.onload = function() { 
    var c = document.getElementById("myCanvas"); 
    var ctx = c.getContext("2d"); 
    var img = new Image(); 
    img.src = "hand.jpg"; 
    img.onload = function() { 
     ctx.drawImage(img, 10, 10,50,50); 

     var imgData = ctx.getImageData(10,10,50,50); 
     for (var i=0;i<imgData.data.length;i+=4){ 
      imgData.data[i]=255-imgData.data[i]; 
      imgData.data[i+1]=255-imgData.data[i+1]; 
      imgData.data[i+2]=255-imgData.data[i+2]; 
      imgData.data[i+3]=255; 
     } 
     ctx.putImageData(imgData,100,100); 
    } 
} 

BTW你可以用

ctx.globalCompositeOperation = "difference"; 
ctx.fillStyle = "white" 
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height); 
ctx.globalCompositeOperation = "source-over"; // restore default 
反轉圖像顏色
+0

非常感謝!我不會期待這一點。現在我有另一個問題。我複製了你的代碼,它說(畫布被交叉源數據污染了)。我知道這是一個常見問題,但是stackoverflow上的所有答案都不適用於我。我只在本地運行這個 –

+1

@UniSoundWaterloo如果你在本地主機上運行,​​確保圖像也來自相同的。如果圖像來自文件存儲區,則無法使用該圖像 – Blindman67

+0

男人,你太棒了! –