Several context properties can be used to set the thickness of the shape outlines, the way line end caps are drawn, etc.
They apply to all shapes that are drawn in path mode (lines, curves, arcs) and some also apply to rectangles.
We have seen this before. This is done by changing the value (in pixels) of the lineWidth property of the context:
ctx.lineWidth = 10; // set the thickness of every shape drawn in stroke/wireframe mode to 10 pixels
Here is a complete example where we draw with a lineWidth of 20 pixels:
Source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A simple example of lineWidth property use</title>
</head>
<body>
<canvas id="myCanvas" width="500">Your browser does not support the canvas tag.</canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// first path
ctx.moveTo(20, 20);
ctx.lineTo(100, 100);
ctx.lineTo(100, 0);
// second part of the path
ctx.moveTo(120, 20);
ctx.lineTo(200, 100);
ctx.lineTo(200, 0);
// indicate stroke color + draw first part of the path
ctx.strokeStyle = "#0000FF";
// Current line thickness is 20 pixels
ctx.lineWidth = 20;
ctx.stroke();
// Draws a rectangle
ctx.strokeRect(230, 10, 100, 100);
</script>
</body>
</html>
The lineCap property of the context indicates the way line end caps are rendered. Possible values are butt (default), round, square (from top to bottom in the next illustration). Note that a value of "round" or "square" makes the lines slightly longer than the default value "butt".
Try this:
Note that in this example, the rectangle is not affected. It has no line ends visible - all its sides meet. However, the next property we're going to look at will have an effect on rectangles!
The lineJoin property of the context indicates the way corners are rendered, when two lines meet. Possible values are miter (the default) for creating sharp corners, round, or bevel for "cut corners".
Try this:
The miterLimit property value corresponds to the maximum miter length: the distance between the inner corner and the outer corner where two lines meet. When the angle of a corner between two lines gets smaller, the miter length grows and can become too long.
In order to avoid this situation, we can set the miterLimit property of the context to a threshold value. If the miter length exceeds the miterLimit value, then the corner will be rendered as if the lineJoin property had been set to "bevel" and the corner will be "cut".
You can try an interactive example here:
In the example, try different values for the miterLimit property. You'll see that the way the corners are rendered changes at values around 2 and 3.