iChwan
iChwan

Reputation: 53

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

`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

Upvotes: 2

Views: 1786

Answers (1)

Here man, i clone your sandbox and make some change on function 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

Upvotes: 2

Related Questions