Canvas Stroke Alignment
This shows how you can apply a stroke on the inside/outside/center of a shape.
by ram64
HTML
<canvas id="myCanvas" width="400" height="400" style="background-color: #00ff00;"></canvas>
JavaScript
var canv; var ctx;
canv = document.getElementById('myCanvas');
ctx = canv.getContext('2d');
ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillStyle = '#0000ff';
ctx.lineWidth = 10;
// 10px Stroke centered
// This is the normal way to do it. The stroke will go half the
// line width on each side of the shape
ctx.fillRect(30, 30, 100, 50);
ctx.strokeRect(30, 30, 100, 50);
// 10px Stroke outside
// This way you need to stroke a shape larger in width and height
// with twice the line width (20px) and offset it on the X and Y with
// half the line width (5px);
ctx.fillRect(30, 130, 100, 50);
ctx.strokeRect(25, 125, 110, 60);
// 10px Stroke inside
// This way you need to stroke a shape smaller in width and height
// with twice the line width (20px) and offset it on the X and Y with
// half the line width (5px);
ctx.fillRect(30, 230, 100, 50);
ctx.strokeRect(35, 235, 90, 40);
// Do the same with a circle
// Circle with centered stroke
ctx.beginPath();
ctx.arc(250, 55, 30, 0, 2*Math.PI);
ctx.fill();
ctx.closePath();
ctx.arc(250, 55, 30, 0, 2*Math.PI);
ctx.stroke()
ctx.closePath();
// Circle with outter stroke
// Depending on how your shape has it's anchor point defined you will
// need or not the position offset.
ctx.beginPath();
ctx.arc(250, 155, 30, 0, 2*Math.PI);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(250, 155, 35, 0, 2*Math.PI);
ctx.stroke()
ctx.closePath();
// Circle with inner stroke
ctx.beginPath();
ctx.arc(250, 255, 30, 0, 2*Math.PI);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(250, 255, 25, 0, 2*Math.PI);
ctx.stroke()
ctx.closePath();