HTML5画布-fillRect()与rect() [英] HTML5 Canvas - fillRect() vs rect()

查看:131
本文介绍了HTML5画布-fillRect()与rect()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,如果我在两个地方都使用rect()然后使用fill()(即两个矩形均为绿色),但是第二个fillStyle会覆盖第一个中指定的颜色(即,两个rects均为绿色),但按预期方式工作(即如果我将第一个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命令,则每个新矩形都将被前面的fillstyle填充.

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是画布的path命令的一部分.

.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命令,则所有.rect都将仅使用最后一个.fillStyle.

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆