javascriptvar

How Would I Make the (x,y,width,height) of a strokeRect a Var?


I'm trying to make a square in a canvas that moves(Tetris), and I want to know if there's an alternative to making a independent fillRect. My line of thought is that I can make the fillRect() position and size based completely off of what the strokeRect is. I'm open to alternatives if there is a better way to do this.

I think it's something like "var strokeX = ctx.strokeRect(xPos);" but I just don't know enough about Java.


Solution

  • If you want to reuse the same shape for the fill and the stroke, you may be better off using paths, which separates the shape from the rendering.

    You start off by calling ctx.beginPath() to start a new path. You can then use various methods to create a path, notably ctx.rect(x, y, width, height) to add a rectangle to the path. Then, you can call ctx.fill() and ctx.stroke() to fill and stroke the most recent path:

    ctx.beginPath();
    ctx.rect(x, y, width, height);
    ctx.fill();
    ctx.stroke();
    

    For more information, see this MDN article and the documentation for rect()