简体   繁体   中英

How to get the Pixel data from the Canvas

I am generating the image from the entered text in the text box. I need to get the pixel from the generated image. Right now I am doing the following

      tCtx.fillText(entered_text, 20, 40);
      imageElem.src = tCtx.canvas.toDataURL("image/png");

      var imageData = tCtx.getImageData(0, 0, tCtx.canvas.width, tCtx.canvas.height);
      var px = imageData.data;      
      var len = px.length;

      for (var i = 0; i < len; i+=4) {
          var redPx = px[i];
          var greenPx = px[i+1];
          var bluePx = px[i+2];
          var alphaPx = px[i+3];
          console.log(redPx,greenPx,bluePx);
      }

Here the console prints the all 0's only for each pixel. But in the Canvas I am seeing the image, when I gave that toDataURL(), in image tag also I am seeing the Image. Don't know how.

When I use the custom images other than the text, then I am getting the pixel data like, 34 45 255 255 54 56 210 255 ...

You need to print Alpha channel to console as well. I also received 0,0,0 for all pixels. Since default canvas's background is (0,0,0,0) which is transparent. And black font is (0,0,0,noneZeroValue): (could be not 255 because of antialising). If you won't print alpha channel all of them will be 0,0,0.

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="100" height="20" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    //ctx.font = "48px serif";
ctx.fillText("A lot of text", 0, 10);
//ctx.drawImage(ocanvas,0,0,c.width,c.height);
var imageData = ctx.getImageData(0, 0, c.width, c.height);
      var px = imageData.data;      
      var len = px.length;

      for (var i = 0; i < len; i+=4) {
          var redPx = px[i];
          var greenPx = px[i+1];
          var bluePx = px[i+2];
          var alphaPx = px[i+3];
          //if (redPx!=0 || greenPx!=0 ||bluePx!=0 || alphaPx!=0){
          console.log(redPx,greenPx,bluePx,alphaPx);


}                  

};


</script>

</body>
</html>

I found the solution. What i did right now is

tCtx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);

because of this I am displaying the image out side of the canvas. So, it is not visible. Then I changed it to

tCtx.putImageData(imageData, 0, 0);

now, it is fine. Able to get the pixel data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM