I want to know how to make background color white.
I built a drawing app with canvas. You can download the canvas image you have drawn by clicking the Download button. But its background color is black (technically transparent).
How can I change it to white?
I added the following code to my code, but it didn't work well. I couldn't draw anything.
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#BADA55';
  ...
function draw(e) {
  if (!isDrawing) return;
  console.log(e);
  ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
  ctx.beginPath();
  ctx.moveTo(lastX, lastY);
  ctx.lineTo(e.offsetX, e.offsetY);
  ctx.stroke();
  [lastX, lastY] = [e.offsetX, e.offsetY];
  ...
}
canvas.addEventListener('mousedown', (e) => {
  isDrawing = true;
  [lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', draw);
  ...
downloadBtn.addEventListener('click', downloadImage);
function downloadImage() {
  if (canvas.msToBlob) {
    const blob = canvas.msToBlob();
    window.navigator.msSaveBlob(blob, filename);
  } else {
      downloadLink.href = canvas.toDataURL('image/png');
      downloadLink.download = filename;
      downloadLink.click();
  }
}
I want to make background color of downloaded image white.
You can use the following code to set background color of canvas.
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillRect(0, 0, canvas.width, canvas.height);canvas{ border: 1px solid black; }<canvas width=300 height=150 id="canvas">If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With