lundi 22 novembre 2021

Can't draw image to canvas in javascript

I'm attempting to put a watermark image on an input image before saving it to a database. I'm using a canvas to do this then convert the canvas back to a blob but when I reference the watermark image in the projects local file directory to draw onto the canvas, I get a "Tainted canvases may not be exported." error in the console.

  // Read input file
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {

// Create canvas & calculate Stamp size and position
const canvas = document.createElement("canvas");
canvas.width = canvasSize.width;
canvas.height = canvasSize.height;
var calcW = canvasSize.width/2;
var calcH = calcW/2.16;
var calcX = (canvasSize.width - calcW)/2;
var calcY = (canvasSize.height - calcH)/2;

// Load input image into canvas
const img = document.createElement("img");
img.src = reader.result;
img.onload = () => {
  const ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);

  //Load & draw the Stamp image
  const mark = new Image();
  mark.src = 'assets/img/compliant.png'; // <<TAINTED ASSET?
  mark.onload = () => {
    ctx.drawImage(mark, calcX,calcY,calcW,calcH);

    // Convert to blob and get URL
    canvas.toBlob((canvasBlob) => {
      const newImg = document.createElement("img"),
      url = URL.createObjectURL(canvasBlob);

      newImg.onload = function () {
        //Destroy objecturl after image loading
        URL.revokeObjectURL(url);
      };

      // Show stamped image
      newImg.src = url;
      window.open(url);
    });
  };
};
};
});



Aucun commentaire:

Enregistrer un commentaire