javascript - HTML5 Canvas - fillRect() vs rect() -
in code below, second fillstyle
overrides color specified in first 1 if use rect()
, fill()
in both places (ie, both rects green) works expected (ie, first rect being blue , second being green) if change first rect()
fillrect()
. why so? thought fillrect()
rect()
, 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();
tested in chrome | fiddle
fillrect
.fillrect "stand-alone" command draws , fills rectangle.
so if issue multiple .fillrect commands multiple .fillstyle commands, each new rect filled preceeding fillstyle.
ctx.fillstyle="red"; ctx.fillrect(10,10,10,10); // filled red ctx.fillstyle="green"; ctx.fillrect(20,20,10,10); // filled green ctx.fillstyle="blue"; ctx.fillrect(30,30,10,10); // filled blue
rect
.rect part of canvas's path commands.
path commands groups of drawings beginning beginpath() , continuing until beginpath() issued.
within each group, last styling command wins.
so if issue multiple .rect commands , multiple .fillstyle commands inside path, last .fillstyle used on .rect's.
ctx.beginpath(); // path commands must begin beginpath ctx.fillstyle="red"; ctx.rect(10,10,10,10); // blue ctx.fillstyle="green"; ctx.rect(20,20,10,10); // blue ctx.fillstyle="blue"; // last fillstyle, "wins" ctx.rect(30,30,10,10); // blue // 1 fillstyle allowed per beginpath, last blue style fills ctx.fill()
Comments
Post a Comment