Home > Mobile >  Download image after load it in Canvas
Download image after load it in Canvas

Time:04-02

I'm try to load image into canvas and text over it, then download it with text.

I successfully load image into canvas and text over it. but when I try to download the image with text it's download black, after many attempts, I tried to ger the canvas's "toDataURL" and discovered it's blank.

I don't know what's the problem, but I think it's get the toDataURL before the image loaded.

here's my piece of code

function addTextToImage(imagePath, text) {
    var circle_canvas = document.getElementById("canvas");
    var context = circle_canvas.getContext("2d");

    // Draw Image function
    var img = new Image();
    img.src = imagePath;
    img.onload = function () {
        context.drawImage(img, 0, 0);
        context.lineWidth = 1;
        context.fillStyle = "#F00";
        context.lineStyle = "#F00";
        context.font = "18px sans-serif";
        context.fillText(text, 50, 50);
    };
    
}
addTextToImage("myImage.jpeg", "My Name is Muhammad");

console.log(circle_canvas.toDataURL());
<canvas id="canvas" width="340" height="340"></canvas>

CodePudding user response:

You have to wait after img is finished loading. Or use async or callback function instead.

function addTextToImage(imagePath, text) {
var circle_canvas = document.getElementById("canvas");
var context = circle_canvas.getContext("2d");

// Draw Image function
var img = new Image();
img.src = imagePath;
img.onload = function () {
    context.drawImage(img, 0, 0);
    context.lineWidth = 1;
    context.fillStyle = "#F00";
    context.lineStyle = "#F00";
    context.font = "18px sans-serif";
    context.fillText(text, 50, 50);
    console.log(circle_canvas.toDataURL());
};
img.setAttribute('crossorigin', 'anonymous');
}

Visit:
https://playcode.io/880411/

Get canvas toDataUrl() after processing Javascript

Tainted canvases may not be exported

CodePudding user response:

try doing this, here I'm doing the downloading process inside the onload event.

function addTextToImage(imagePath, text) {
      var circle_canvas = document.getElementById("canvas");
      var context = circle_canvas.getContext("2d");

      // Draw Image function
     var img = new Image();
     img.src = imagePath;
     img.onload = function () {
        context.drawImage(img, 0, 0);
        context.lineWidth = 1;
        context.fillStyle = "#F00";
        context.lineStyle = "#F00";
        context.font = "18px sans-serif";
        context.fillText(text, 50, 50);

        // after image loads
        let fileName = `ImageName.png`
        const link = document.createElement('a')
        link.href = circle_canvas.toDataURL("image/png").replace("image/png", 
         "image/octet-stream")
        link.download = fileName
        link.click();
    
   };

}
 addTextToImage("myImage.jpeg", "My Name is Muhammad");
  • Related