HTML5 Canvas - fillRect() vs rect()

前端 未结 3 1106
一向
一向 2020-12-18 19:58

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,

相关标签:
3条回答
  • 2020-12-18 20:18

    fillRect

    .fillRect is a "stand-alone" command that draws and fills a rectangle.

    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.

    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.

    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()
    
    0 讨论(0)
  • 2020-12-18 20:21

    If you want different colors for different path commands, calling beginPath() before each command works.

    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()
    
    0 讨论(0)
  • 2020-12-18 20:24

    As I know there are 3 "rect" functions for canvas: fillRect, strokeRect and 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
    

    There are two shortcuts:

    ctx.strokeRect(0,0,rectWidth,rectHeight); // shortcut to stroke rectangle
    ctx.fillRect(0, 0, rectWidth, rectHeight); // shortcut to fill rectangle
    

    So, your fill invocation could fill only your shape created with rect.

    0 讨论(0)
提交回复
热议问题