Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make background color of canvas white with JavaScript?

What I want to do

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?


What I tried

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);

Here is my code

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.

like image 863
Miu Avatar asked Sep 12 '25 00:09

Miu


1 Answers

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">
like image 94
Priyesh Diukar Avatar answered Sep 14 '25 15:09

Priyesh Diukar