我有下面的代码,它首先绘制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>

推荐答案

这关系到画布的current default path.有only one个.由于不关闭一条路径并开始另一条路径,因此entire path(即两组矩形)将呈现为蓝色.

这条路的第一部分看起来就像

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>

Javascript相关问答推荐

vanillajs-datepicker未设置输入值,日期单击时未触发更改事件

如何在表格上拥有水平滚动条,在正文页面上拥有垂直滚动条,同时还对html表格的标题使用位置粘性?

为什么我的includes声明需要整个字符串?

如何修复(或忽略)HTML模板中的TypeScript错误?'

虚拟滚动实现使向下滚动可滚动到末尾

Prisma具有至少一个值的多对多关系

S文本内容和值不必要的不同

如果Arrow函数返回函数,而不是为useEffect返回NULL,则会出现错误

在HTML语言中调用外部JavaScript文件中的函数

闭包是将值复制到内存的另一个位置吗?

如何将未排序的元素追加到数组的末尾?

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

元素字符串长度html

JavaScript不重定向配置的PATH

使用API调用的VUE 3键盘输入同步问题

为什么我看到的是回复,而不是我的文档?

如何使用[ModelJSON,ArrayBuffer]调用tf.loadGraphModelSync

从异步操作返回对象

是否有静态版本的`instanceof`?

如何创建一个for循环,用于计算仪器刻度长度并将其放入一个HTML表中?