html 使用< img>js获取数据字符串/缓冲区,无需额外的网络调用

olqngx59  于 2023-04-04  发布在  其他
关注(0)|答案(1)|浏览(139)

我看到了以下使用canvasimg获取图像数据字符串的方法:

let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
context.drawImage(img, 0, 0 );
let theData = context.getImageData(0, 0, img.width, img.height);
console.log("Data from img: " + theData);

但是这总共导致两个网络调用图像;第一个来自img标签本身(成功),另一个来自canvas(不成功,CORS)。
是否有办法访问已加载到img标记中的图像数据,或者我必须进行额外的调用?

nbewdwxp

nbewdwxp1#

您可以将图像元素的crossOrigin属性设置为`“Anonymous”来解决这个问题。

<html>
<head>
<title></title>
</head>
<body>
<script>
let imageURL = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2Fmdn_logo-only_color.svg?1535749917189";

var downloadedImg = new Image();
downloadedImg.crossOrigin = "Anonymous";
downloadedImg.addEventListener("load", ()=> {
  try {
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");

      canvas.width = downloadedImg.width;
      canvas.height = downloadedImg.height;
      canvas.innerText = downloadedImg.alt;

      context.drawImage(downloadedImg, 0, 0);
      document.body.innerText = canvas.toDataURL("image/png");
  } catch (err) {
    document.body.innerText = `Error: ${err}`;
  }
}, false);
downloadedImg.src = imageURL;
</script>
</body>
</html>

相关问题