我有下面的代码,它首先绘制3个黄色小矩形,然后绘制一个大的蓝色矩形.我在最后一次绘制之前更改了填充样式属性.因此,所有矩形都是蓝色的. 如果没有执行最后一次绘制(在第二个循环中注释掉了ctx.ill),那么我会看到3个黄色矩形.
const get = id => document.getElementById(id);
const canv = get('canv');
const [w, h] = [canv.width, canv.height];
const ctx = canv.getContext("2d");
ctx.fillStyle = 'yellow';
for (let x = 0; x < 3; x++) {
ctx.rect(10*x, 100, 3, 3);
ctx.fill();
}
ctx.fillStyle = 'blue';
for (let x = 0; x < 1; x++) {
ctx.rect(10*x + 100, 100, 5, 5);
ctx.fill();
}
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body {
background-color: #020408;
color: #ccc;
}
<canvas id="canv" width="200" height="200" style="border: solid 1px grey"></canvas>