JSFiddle - React, Tailwind, and code Playground

by Adolfo

HTML

<!-- 
https://stackoverflow.com/questions/38173871/html5-canvas-how-to-border-a-fillrect
-->


<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));
}