如何使用JavaScript将画布的背景颜色设为白色?

时间:2019-05-16 18:02:00

标签: javascript canvas

我想做什么

我想知道如何将背景色设为白色。

我用画布构建了一个绘图应用程序。您可以通过单击下载按钮下载绘制的画布图像。但是它的背景色是黑色的(技术上是透明的)。

如何将其更改为白色?


我尝试过的

我在代码中添加了以下代码,但是效果不佳。我什么都画不出来。

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

我想将下载图像的背景颜色设为白色。

3 个答案:

答案 0 :(得分:0)

您可以使用以下代码设置画布的背景颜色。

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">

答案 1 :(得分:0)

在画布上,您可以使用getAttribute()来检索尺寸。看看我的代码段:

let canvas = document.getElementById('canvas');
let cheight = parseInt(canvas.getAttribute("height"));
let cwidth = parseInt(canvas.getAttribute("width"));

let context = canvas.getContext('2d');

context.fillStyle = "green";
context.fillRect(0,0,cwidth,cheight);
<canvas width="200" height="200" id="canvas">

答案 2 :(得分:0)

在您的draw()函数中,您需要像这样专门添加背景:

const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#BADA55';
ctx.fillStyle = "#ffffff"; //HERE, use HEX format in 6 digits
ctx.fillRect(0, 0, canvas.width, canvas.height); //HERE

 ...

function draw(e) {
    ...
}

为什么?

  

您需要在所有内容之前绘制背景,否则一遍又一遍地绘制背景,或者在所有内容之上绘制背景,将导致白色矩形与画布上的所有内容重叠。

这里是LIVE DEMO