HTML5 canvas: How to close fillRect?

In HTML5, I want to do fillRect()(with white fill color) and border(black). I do not want to use strokeRect()it if I cannot fill it out later. I make a game where you click on the squares and they change color (this is harder than what it focuses on).

<canvas id="canvas1" width="400" height="300" style="border:1px solid #000000;"></canvas>
    <script>
        var c=document.getElementById("canvas1");
        var ctx=c.getContext("2d");
        ctx.strokeStyle="rgba(0,0,0,1)";
        ctx.strokeRect(0,0,100,100);
    </script>

The border around the canvas is for reference. I can use CSS too, but now everything is in HTML.

+4
source share
2 answers

, . , , 2 2, . , , , ,

HTML

<canvas id="canvas1" width="400" height="300" style="border:1px solid #000000;"></canvas>

CSS

#canvas1{
  border: solid 1px black;
}

Javascript

var c=document.getElementById("canvas1");
var ctx=c.getContext("2d");

var rectXPos = 50;
var rectYPos = 50;
var rectWidth = 100;
var rectHeight = 100;

drawBorder(rectXPos, rectYPos, rectWidth, rectHeight)

ctx.fillStyle='#FFF';
ctx.fillRect(rectXPos, rectYPos, rectWidth, rectHeight);

function drawBorder(xPos, yPos, width, height, thickness = 1)
{
  ctx.fillStyle='#000';
  ctx.fillRect(xPos - (thickness), yPos - (thickness), width + (thickness * 2), height + (thickness * 2));
}

jsfiddle link: https://jsfiddle.net/jxgw19sh/2/

- -

drawBorder, thickness, 1, thickness , 1.

+3

. - , . - :

ctx.fillStyle = 'blue';
ctx.strokeStyle = 'red';
var fillRect = false;
ctx.rect(20, 20, 150, 100);
if (fillRect) {
  ctx.fill();
}
ctx.stroke();

, fillRect true, . requestAnimationFrame.

, , , paper.js. , , , , , , .

+4

All Articles