简体   繁体   English

使用 Reactjs 在画布上绘制图像后无法将画布转换为图像

[英]Can't convert canvas to image after draw image on canvas with Reactjs

i'm trying to draw image on canvas and convert it to image with my react app, but when i click on download button i getting this error我正在尝试在画布上绘制图像并使用我的 React 应用程序将其转换为图像,但是当我单击下载按钮时出现此错误

`Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.`

here is my code draw image function这是我的代码绘制图像功能

const printLocation = _ => {
    let canvas = canvasRef.current;
    let context = canvas.getContext("2d");
    let img = new Image();
    img.src = "https://kilausenja.com/wp-content/uploads/2019/04/18-02-08-17-29-50-859_deco.jpg";
    context.drawImage(img, 0, 0, 100, 100);
  };

convert canvas to image function将画布转换为图像功能

  const canvasToImg = _ => {
    let canvas = canvasRef.current;
    let tagA = document.createElement("a");
    document.body.appendChild(tagA);
    tagA.href = canvas.toDataURL();
    tagA.download = "canvas-image.png";
    tagA.click();
    document.body.removeChild(tagA);
  };

and here is my codesandbox example这是我的代码和框示例

Here man, i clone your sandbox and make some change on function printLocation伙计,我克隆了你的沙箱并对函数 printLocation 进行了一些更改

edited version编辑过的版本

  img.crossOrigin = "anonymous";
  img.src = "https://2.bp.blogspot.com/-VTIlinKHDHE/WXiij8jFF-I/AAAAAAAADvs/r2yZ6H6QomUfR_kNBW0F-638aCj98XZvACLcBGAs/s1600/hasil%2Bscan%2B1%2B-%2Bcara%2Bscan%2Btanda%2Btangan.jpg";

remember for the source of image, because not any server allow you to make a cross origin request请记住图像的来源,因为没有任何服务器允许您进行跨源请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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