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">
如果您想要明确地设置背景,您必须确定在画布上绘制当前元素的后面。
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);
你可以通过以下方式更改画布的背景:
<head>
<style>
canvas {
background-color: blue;
}
</style>
</head>
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>
我们不需要访问画布上下文。
如果使用纯JS实现 hednek,你会得到这样的代码:canvas.setAttribute('style', 'background-color:#00F8')
。但是我更喜欢的方法需要将kabab-case转换为camelCase。
canvas.style.backgroundColor = '#00F8'
<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>
sketch.js 文件
function setup() {
createCanvas(windowWidth, windowHeight);
background(r, g, b);
}
p5.js
经过压缩和 gzip 处理后只有 340kB
!我认为这个页面包含了一些更轻量级的选项。 - kano
ctx.fillStyle="rgb(0,0,255)"
fillStyle。 - Carson