我想做的事我想知道如何使背景颜色变白。我用画布构建了一个绘图应用程序。您可以通过单击“下载”按钮下载已绘制的画布图像。但它的背景颜色是黑色(技术上透明)。如何将其更改为白色?我尝试了什么我在代码中添加了以下代码,但效果不佳。我无法画任何东西。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 回答
慕的地6264312
TA贡献1817条经验 获得超6个赞
您可以使用以下代码设置画布的背景颜色。
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">
三国纷争
TA贡献1804条经验 获得超7个赞
在画布上,您可以使用它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">
添加回答
举报
0/150
提交
取消