HTML5 Canvas - fillRect() vs rect()
HTML5 Canvas - fillRect() vs rect()
在下面的代码中,第二个fillStyle
覆盖了在第一个指定的颜色,如果我使用rect()
,然后在两个地方fill()
(即,两个矩形都是绿色的),但工作如预期(即,第一个矩形是蓝色的,第二个是绿色的),如果我改变第一个rect()
为fillRect()
。为什么会这样呢?我以为fillRect()
只是rect()
然后是fill()
,对吗?
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测试 | Fiddle
fillRect
。fillRect是一个"独立的"命令,用于绘制和填充矩形。
所以如果你用多个。fillstyle命令发出多个。fillrect命令,每个新的rect将被前面的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是画布路径命令的一部分。
路径命令是组图纸从beginPath()开始,一直持续到发出另一个beginPath()。
在每个组中,只有最后一个样式命令获胜。
所以如果你在一个路径中发出多个。rect命令和多个。fillstyle命令,只有最后一个。fillstyle会被用于所有的。rect。
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()
据我所知,画布有3个"rect"函数:fillRect
, strokeRect
和rect
。
ctx.rect(0,0,rectWidth,rectHeight); // create some shape, there is nothing on the canvas yet
ctx.stroke(); // draw stroke of the shape
ctx.fill(); // fill the shape
有两个快捷键:
ctx.strokeRect(0,0,rectWidth,rectHeight); // shortcut to stroke rectangle
ctx.fillRect(0, 0, rectWidth, rectHeight); // shortcut to fill rectangle
所以,你的fill
调用只能填充用rect
创建的形状
如果您希望不同路径命令的颜色不同,请在每个命令工作之前调用beginPath()
。
ctx.beginPath();
ctx.fillStyle="red";
ctx.rect(10,10,10,10);
ctx.fill()
ctx.beginPath()
ctx.fillStyle="green";
ctx.rect(20,20,10,10);
ctx.fill()
ctx.beginPath()
ctx.fillStyle="blue";
ctx.rect(30,30,10,10);
ctx.fill()
相关文章:
- setInteval vs setTimeout
- $(this).prop('property') vs. this.property
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- Js.erb VS按钮标记-不'不起作用.为什么?
- reactjs this.refs vs document.getElementById
- renderReact/Rect Router+Node/Express.js的服务器端/同构渲染中未定义renderP
- D3.JS向rect添加缩放和列表项
- Performance: NaCl vs Emscripten
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- Advantages to DOMParser vs template & innerHTML
- JavaScript-===vs===运算符性能
- 开发第三方小部件-Angular vs jQuery vs普通的旧JS
- PhantomJS(vs nightwatch.js)设置cookie错误
- D3JS selectAll to append rect
- Javascript events: window.event vs argument reference (funct
- 从联合js rect对象调用引导模式
- 需要确认我对Servlet vs RESTful网页的理解's的差异
- "#"keyCode=222 vs 51(Chrome与Android版Chrome)-为什么有区别
- .notion vs.[]notation |插入到文本对象中
- HTML5 Canvas - fillRect() vs rect()