如何使用JavaScript将画布的背景颜色设为白色? [英] How can I make background color of canvas white with JavaScript?

查看:33
本文介绍了如何使用JavaScript将画布的背景颜色设为白色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何将其更改为白色?

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

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.

推荐答案

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

In your draw() function you need to add specifically the background like this:

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) {
    ...
}

为什么?

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

You need to draw the background before everything, otherwise drawing the background over and over, or also above everything would result in the white rectangle overlapping everything on your canvas.

这是实时演示.

这篇关于如何使用JavaScript将画布的背景颜色设为白色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆