如何获取外部上传图像的ImageData?

时间:2016-06-16 12:31:39

标签: javascript html html5 html5-canvas

enter image description here

我想得到上面图片的ImageData。作为回报,我没有得到任何数据。我试图执行的代码附在下面。



function drawImage(imageObj) {
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var imageX = 69;
        var imageY = 50;
        var imageWidth = imageObj.width;
        var imageHeight = imageObj.height;

        context.drawImage(imageObj, imageX, imageY);

        var imageData = context.getImageData(10, 10, 50, 50);
        var data = imageData.data;

        // iterate over all pixels
        for(var i = 0, n = data.length; i < n; i += 4) {
          var red = data[i];
          var green = data[i + 1];
          var blue = data[i + 2];
          var alpha = data[i + 3];
          alert(red + " " + green + " " + blue + " " + alpha);
        }

       
       
      }
      var imageObj = new Image();
      imageObj.onload = function() {
        drawImage(this);
      };
      imageObj.src = 'Images/graph.gif'
&#13;
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
  </body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您没有获得任何数据,因为您的画布上没有任何图纸。

您正在向右绘制69像素,仅获取最左边的60像素。

var imageX = 69;
var imageY = 50;

// drawing image starting at x=69
context.drawImage(imageObj, imageX, imageY);

...

// fetching image data from x=10 through x=60 (Nothing is drawn here!)
var imageData = context.getImageData(10, 10, 50, 50);
顺便说一句,你实际上是在获取数据,但画布的空白部分总是会返回红色,绿色,蓝色和蓝色的零。 alpha组件。