如何获取Canvas图像数据?

时间:2017-01-30 04:46:56

标签: javascript jquery canvas

我正在尝试读取图像数据但每次都给我空白数组。

我所做的是加载图像的黑白颜色,当我检查控制台日志的数组输出时,它总是空白

// function to convert rgb to hex
    function rgbToHex(r, g, b) {
        if (r > 255 || g > 255 || b > 255)
            throw "Invalid color component";
        return ((r << 16) | (g << 8) | b).toString(16);
    }
// load image to canvas 
     function Load_mg(can_id,mg_src) {
        var ctx = document.getElementById(can_id);
        if (ctx.getContext) {
            ctx = ctx.getContext('2d');
            var img1 = new Image();
            img1.onload = function () {
                ctx.drawImage(img1, 0, 0);
            };
            img1.src = mg_src;
        }
    var can_ida = document.getElementById(can_id);  
    //var imgData = ctx.getImageData(0,0,can_ida.width,can_ida.height);
     var imgData = ctx.getImageData(10, 10, 50, 50);
    var data = imgData.data;    

    for(var i=0; i<data.length; i+=4) {
      var red = data[i];
      var green = data[i+1];
      var blue = data[i+2];
      var alpha = data[i+3];
      if(red != 0){
      console.log('some color found');
      break;
      }
      var hex = "#" + ("000000" + rgbToHex(red,green, blue)).slice(-6);
    //  console.log('can_data hex '+hex+' Alpha '+alpha);
      //if(i === 1000)break;  
    }

    console.log(data);

    } // function end point
    Load_mg('test1','box_1.png');

小提琴:Jsbin

在小提琴我通过base64图像数据加载图像

1 个答案:

答案 0 :(得分:1)

要解决此问题,只需将获取像素代码移动到onload事件中即可。

// function to convert rgb to hex
function rgbToHex(r, g, b) {
    return "#" + (r < 10 ? "0" : "") + r.toString(16) +
           (g < 10 ? "0" : "") + g.toString(16) +
           (b < 10 ? "0" : "") + b.toString(16);
}
// load image to canvas
function Load_mg(can_id, mg_src) {
    var ctx = document.getElementById(can_id);
    if (ctx.getContext) {
        ctx = ctx.getContext('2d');
        var img1 = new Image();
        img1.onload = function () {
            ctx.drawImage(this, 0, 0);
            var can_ida = document.getElementById(can_id);
            //var imgData = ctx.getImageData(0,0,can_ida.width,can_ida.height);
            var imgData = ctx.getImageData(10, 10, 50, 50);
            var data = imgData.data;

            for (var i = 0; i < data.length; i += 4) {
                var red = data[i];
                var green = data[i + 1];
                var blue = data[i + 2];
                var alpha = data[i + 3];
                if (red != 0) {
                    console.log('some color found');
                    break;
                }
                var hex = rgbToHex(red, green, blue);
            }
        };
        img1.src = mg_src;
    }

}
Load_mg('test1', 'box_1.png');