I. Golsby I. Golsby - 8 months ago 126
Javascript Question

HTML5 Canvas: How to border a fillRect?

In HTML5, I want to make a

(with a white fill color) and a
(black). I don't want to use
unless I can fill that later. I'm making a game where you click on squares and they change color (it's more complex than that but that's what this focuses on).

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

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


Work out the position you want to draw the square with the width and height. Once you have done that simply draw a bigger square first which has wider by 2 and higher by 2 but with the same center point. So you draw a square which is bigger and then you draw the normal square on top, this then gives you the illusion of the square has a border


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


  border: solid 1px black;


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.fillRect(rectXPos, rectYPos, rectWidth, rectHeight);

function drawBorder(xPos, yPos, width, height)
  ctx.fillRect(xPos - 1, yPos - 1, width + 2, height + 2);

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