Search code examples
javascriptcanvasdrawimagegetimagedata

JavaScript canvas drawImage getImageData


I cannot reach an understanding of how 2 methods work with canvas: drawImage getImageData in fact, I would like to parse the bitmap image into an array of RGBA points, be able to convert it and display it using the putImageData method. But only one thing works: drawImage or getImageData. I ask for help - explain how these methods influence each other.

<!DOCTYPE html>
    <html lang="en">
     <head>
      <meta charset="UTF-8">
      <title> Canvas to array </title>
     </head>
<body>
    <canvas id="canvas" width="1200" height="600" />
    <script>
      "use strict"
      let imageData;
      let My_img = new Image();
      My_img.src = 'test1.jpg';
      let cnv = document.getElementById("canvas");
      let ctx = cnv.getContext("2d");
      My_img.onload = function() {
          ctx.drawImage(My_img, 0, 0);
          imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
          for (let i=0; i<imageData.data.length; i+=4){
             imageData.data[i]=0;
             imageData.data[i+1]=255;
             imageData.data[i+2]=0;
             imageData.data[i+3]=222;
          }
         ctx.putImageData(imageData,300,300);
      };
    </script>
</body>
</html>

Solution

  • You need to set the cross-origin flag on the image object to be "Anonymous".

    My_img.crossOrigin = "Anonymous";
    

    See also: How to fix getImageData() error The canvas has been tainted by cross-origin data?

    Demo

    let ctx = document.getElementById("canvas").getContext("2d");
    let img = new Image();
    img.crossOrigin = "Anonymous";
    img.src = 'https://placekitten.com/200/138';
    img.onload = function() {
      ctx.drawImage(img, 0, 0);
      setTimeout(() => filterImage(ctx), 1000);
    };
    
    // Multiply the value of the red channel by 2 and the blue channel by 3.
    function filterImage(ctx) {
      let d = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
      for (let i = 0; i < d.data.length; i += 4) {
        d.data[i + 0] = Math.min(Math.floor(d.data[i + 0] * 2.0), 0xFF); // R
        d.data[i + 1] = Math.min(Math.floor(d.data[i + 1] * 1.0), 0xFF); // G
        d.data[i + 2] = Math.min(Math.floor(d.data[i + 2] * 3.0), 0xFF); // B
        d.data[i + 3] = 0xFF;                                            // A
      }
      ctx.putImageData(d, 0, 0);
    }
    <canvas id="canvas" width="200" height="138" />