HTML5 Canvas - fillRect() vs rect()(HTML5 画布 - fillRect() 与 rect())
问题描述
在下面的代码中,如果我使用 rect()
然后使用 fill()
,第二个 fillStyle
会覆盖第一个中指定的颜色在这两个地方(即,两个矩形都是绿色的)但如果我将第一个 rect()
更改为 fillRect(),则按预期工作(即,第一个矩形是蓝色,第二个是绿色)代码>.为什么会这样?我以为
fillRect()
只是 rect()
然后是 fill()
,对吧?
In the code below, the second fillStyle
overrides the color specified in first one if I use rect()
and then fill()
in both places (ie, both rects are green) but works as expected (ie, the first rect being blue and second being green) if I change the first rect()
to fillRect()
. Why is it so? I thought fillRect()
was just rect()
and then fill()
, right?
ctx.translate(canvas.width/2, canvas.height/2);
ctx.fillStyle = "#5A9BDC";
ctx.fillRect(0, 0, rectWidth, rectHeight);
// ctx.rect(0, 0, rectWidth, rectHeight);
// ctx.fill();
ctx.translate(-canvas.width/2, -canvas.height/2);
ctx.fillStyle = "#31B131";
ctx.rect(0, 0, rectWidth, rectHeight);
ctx.fill();
在 Chrome 中测试 |小提琴
推荐答案
fillRect
.fillRect 是一个独立"命令,用于绘制和填充矩形.
.fillRect is a "stand-alone" command that draws and fills a rectangle.
因此,如果您使用多个 .fillStyle 命令发出多个 .fillRect 命令,则每个新矩形都将被前面的填充样式填充.
So if you issue multiple .fillRect commands with multiple .fillStyle commands, each new rect will be filled with the preceeding fillstyle.
ctx.fillStyle="red";
ctx.fillRect(10,10,10,10); // filled with red
ctx.fillStyle="green";
ctx.fillRect(20,20,10,10); // filled with green
ctx.fillStyle="blue";
ctx.fillRect(30,30,10,10); // filled with blue
矩形
.rect 是画布路径命令的一部分.
.rect is part of the canvas's path commands.
路径命令是绘图组,从 beginPath() 开始,一直持续到另一个 beginPath() 发出.
Path commands are groups of drawings beginning with the beginPath() and continuing until another beginPath() is issued.
在每个组中,只有最后一个样式命令获胜.
Within each group, only the last styling command wins.
因此,如果您在一个路径中发出多个 .rect 命令和多个 .fillStyle 命令,则只有最后一个 .fillStyle 将用于所有 .rect.
So if you issue multiple .rect commands and multiple .fillStyle commands inside a path, only the last .fillStyle will be used on all the .rect's.
ctx.beginPath(); // path commands must begin with beginPath
ctx.fillStyle="red";
ctx.rect(10,10,10,10); // blue
ctx.fillStyle="green";
ctx.rect(20,20,10,10); // blue
ctx.fillStyle="blue"; // this is the last fillStyle, so it "wins"
ctx.rect(30,30,10,10); // blue
// only 1 fillStyle is allowed per beginPath, so the last blue style fills all
ctx.fill()
这篇关于HTML5 画布 - fillRect() 与 rect()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HTML5 画布 - fillRect() 与 rect()


基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01