Home > Net >  Downloading canvas with border sytle
Downloading canvas with border sytle

Time:05-10

I want to download canvas with border. On screen Canvas has border but when I download canvas, its border doesnt appear

let canvas=qrRef.current.querySelector("canvas")
canvas.style.border="black 30px solid"
 if(type=="PNG"){
    let image=canvas.toDataURL("image/png")
    let anchor=document.createElement("a");
    anchor.href=image;
    anchor.download=`qr-pollective.png`
    document.body.appendChild(anchor);
    anchor.click()
    document.body.removeChild(anchor)
}

console.log(canvas)

<canvas height="400" width="400" style="border: 30px solid black; border-radius: 5px; border-collapse: collapse;">

CodePudding user response:

What you can do is create a bigger canvas which has space for the black border.

Then copy the canvas you have created onto this bigger one, offset by 30px to make room for the border.

Then draw the 4 black rectangles that make up the border. This bigger canvas is then the one that you want to download.

const canvas = document.querySelector('canvas');
const biggerCanvas = document.createElement('canvas');
const w = canvas.width   60;
const h = canvas.height   60;
biggerCanvas.width = w;
biggerCanvas.height = h;
const ctx = biggerCanvas.getContext('2d');
ctx.drawImage(canvas, 30, 30);
ctx.beginPath();
ctx.rect(0, 0, w, 30);
ctx.fillStyle = "black";
ctx.fill();
ctx.rect(0, 0, 30, h);
ctx.fill();
ctx.rect(w - 30, 0, w - 30, h);
ctx.fill();
ctx.rect(0, h - 30, w, h);
ctx.fill();
document.body.append(biggerCanvas); //just to show it has drawn the border
<canvas height="400" width="400" style="border: 30px solid black; border-radius: 5px; border-collapse: collapse;">

CodePudding user response:

I solved my problem with html2canvas here is my code

html2canvas(canvas,{backgroundColor: "transparent"}).then(function (canvas) {
           var myImage = canvas.toDataURL();
           downloadURI(myImage, `qr-pollective.png`);
});

function downloadURI(uri, name) {
      var link = document.createElement("a");
   
      link.download = name;
      link.href = uri;
      document.body.appendChild(link);
      link.click();   

    }
  • Related