1

window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(180, 180, 40, 40);
}

function saveWithBackground(canvas) {
var link = document.createElement("a");
link.href = canvas.toDataURL();
link.download = "download.jpg";
link.click();
}
#canvas {
border: 1px solid black;
background-color: red;
}
<canvas id="canvas" width="400" height="400"></canvas>
<button onclick="saveWithBackground(document.getElementById('canvas'))">Save</button>
but this does not save the image with the background.

Can someone tell me how to save it with background color?

Shem
  • 29
  • 3

1 Answers1

0

you should set the background in canvas.

window.onload = function () {
    var ctx = document.getElementById("canvas").getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 400, 400);
    ctx.fillStyle = "black";
    ctx.fillRect(180, 180, 40, 40);
}
Q.J.
  • 1
  • 2