如何用特定的颜色填充整个画布?

如何用一种颜色填充整个 HTML5 <canvas>

我看到了一些解决方案,如 这个使用 CSS 改变背景颜色,但这不是一个好的解决方案,因为画布仍然是透明的,唯一改变的是它所占据的空间的颜色。

另一种方法是在画布内部创建一个带有颜色的东西,例如,一个矩形(看这里) ,但它仍然没有用颜色填充整个画布(如果画布比我们创建的形状大)。

有没有一个解决方案来填补整个画布与特定的颜色?

233186 次浏览

是的,在画布上用纯色填充矩形,使用画布本身的 heightwidth:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas{ border: 1px solid black; }
<canvas width=300 height=150 id="canvas">

let canvas = document.getElementById('canvas');
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
let ctx = canvas.getContext('2d');


//Draw Canvas Fill mode
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,canvas.width, canvas.height);
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; }
<canvas id='canvas'></canvas>

你可以通过以下方法改变画布的背景:

<head>
<style>
canvas {
background-color: blue;
}
</style>
</head>

你知道吗,有一个完整的画布图形库,叫做 p5.js 只需在 head 元素中添加一行代码和一个附加的素描.js 文件就可以添加它。

首先对 html 和 body 标记执行以下操作:

<html style="margin:0 ; padding:0">
<body style="margin:0 ; padding:0">

把这个加到你的头上:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>

Js 文件

function setup() {
createCanvas(windowWidth, windowHeight);
background(r, g, b);
}

如果要做背景 明确地,必须确保在画布上绘制当前元素 后面

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

我们不需要访问画布上下文。

在纯 JS 中实现 Hednek可以得到 canvas.setAttribute('style', 'background-color:#00F8'),但是我的首选方法需要将 烤肉架转换为 骆驼箱

canvas.style.backgroundColor = '#00F8'