画布获取图像数据始终为

时间:2016-09-19 22:46:57

标签: html5 canvas html5-canvas getimagedata putimagedata

我试图反转图像的颜色。现在图像加载正常,但是当我尝试将getImageData和putImageData调回画布时。画布只是空白。然后我打印出所有的imageData,看起来由于某种原因总是0。我对此感到非常不安。请提前帮助和thx!

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

1 个答案:

答案 0 :(得分: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);
    } 
}

顺便说一句,你可以用

反转图像颜色
ctx.globalCompositeOperation = "difference";
ctx.fillStyle = "white"
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.globalCompositeOperation = "source-over"; // restore default