为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 JavaScript 中将下载的画布图像的背景颜色设为白色?

如何在 JavaScript 中将下载的画布图像的背景颜色设为白色?

一只斗牛犬 2021-05-31 09:39:46
我想做的事我想知道如何使背景颜色变白。我用画布构建了一个绘图应用程序。您可以在按住左键单击的同时移动鼠标在画布上进行绘制。您还可以通过单击下载按钮下载您绘制的画布图像。但它的背景颜色是黑色(技术上透明)。怎么改成白色?我在此之前发布了同样的问题。我被建议打开另一个问题,因为我之前的问题中缺少大部分代码。这个问题有更多细节。我试过的我将以下代码添加到我的代码中,但效果不佳。我什么也画不出来。ctx.fillStyle = "#fff";ctx.fillRect(0, 0, canvas.width, canvas.height);这是我的代码HTML<button class="btn--download">Download</button><canvas id="draw" width="640" height="640"></canvas><a id="download_link"></a>CSS#draw {  display: block;  margin: 0 auto;  background: #fff;  border-radius: 0.3em;  box-shadow: 0 0.1rem 0.5rem 0.1rem rgba(43, 12, 1, 0.1);}JavaScript// Canvasconst canvas = document.querySelector('#draw');const ctx = canvas.getContext('2d');ctx.strokeStyle = '#BADA55';ctx.lineJoin = 'round';ctx.lineCap = 'round';ctx.globalCompositeOperation = 'hue';// ctx.fillStyle = "#fff";// ctx.fillRect(0, 0, canvas.width, canvas.height);// I removed fillStyle & fillRect because I couldn't draw anything due to them.let isDrawing = false;let lastX = 0;let lastY = 0;function draw(e) {  if (!isDrawing) return; // Stop the fn from running when they are not moused down.  console.log(e);  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);canvas.addEventListener('mouseup', () => isDrawing = false);canvas.addEventListener('mouseout', () => isDrawing = false);我想将下载图像的背景颜色设为白色。
查看完整描述

2 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

删除此行

ctx.globalCompositeOperation = 'hue';

这就是使您的笔触在白色背景上呈白色的原因。


查看完整回答
反对 回复 2021-06-03
  • 2 回答
  • 0 关注
  • 234 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信