为什么在 canvas 2D 中更改 fillStyle 会改变先前绘制的矩形的颜色?

问题描述 投票:0回答:1

我有以下代码,首先绘制 3 个黄色的小矩形,然后绘制一个蓝色的大矩形。我在最后一张图之前更改了 fillStyle 属性。结果,所有矩形都是蓝色的。 如果没有执行最后一次绘图(ctx.fill 在第二个循环中被注释掉),那么我会看到 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>

javascript html5-canvas
1个回答
1
投票

这涉及画布的当前默认路径。有只有一个。由于您没有关闭一条路径并开始另一条路径,整个路径(即两组矩形)呈现为蓝色。

只是路径的第一部分看起来像

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();
}
* {
  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>

添加

beginPath
解决问题。

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.beginPath();
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>

© www.soinside.com 2019 - 2024. All rights reserved.