JavaScript canvas drawImage getImageData

JavaScript canvas drawImage getImageData

我无法理解 2 种方法如何与 canvas 一起工作: 绘制图像 获取图像数据 事实上,我想将位图图像解析为 RGBA 点数组,能够使用 putImageData 方法对其进行转换和显示。 但只有一件事有效:drawImage 或 getImageData。 我寻求帮助 - 解释这些方法如何相互影响。

<!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>

您需要将图像对象的跨源标志设置为"Anonymous"。

My_img.crossOrigin = "Anonymous";

另请参阅:How to fix getImageData() error The canvas has been tainted by cross-origin data?

演示

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" />