HTML5 Canvas line and rectangles
3 min readApr 14, 2021
Canvas primitives
Let’s start from something really easy.
This is our basic html with style.css and script.js
<html lang="en">
<head>
<title>Canvas1</title>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet">
</head>
<body>
<canvas id="c1">
Canvas does not work in the old browser message
</canvas>
<script src="script.js"></script>
</body>
</html>
Note here the DOM element Canvas.
Our style
#c1 {
border: 1px solid;
display: block;
width: 600px;
height: 300px;
margin: 0 auto;
}
Our initial canvas
Let’s try to add a few basic primitives
All our elements we ll be added in the script.js file.
Get initial canvas by id and the context
//Definitions
let canvas = document.getElementById('c1');
let context = canvas.getContext("2d");
Now we are ready to add new elements to canvas.
Canvas Rectangle
Let’s add three rectangles
//Red rectangle
context.fillStyle = "red";
context.fillRect(10, 10, 50, 100);
//Yellow rectangle
context.fillStyle = "yellow";
context.fillRect(60, 10, 100, 100);
//Green rectangle
context.fillStyle = "green";
context.fillRect(150, 50, 20, 20);
Canvas Line
We add one white line with width 4.
//Draw line
context.beginPath();
context.strokeStyle = "white";
context.lineWidth = 4;
context.moveTo(20, 20);
context.lineTo(30, 50);
context.stroke();
Possible line cap
context.lineCap = "butt";
//context.lineCap = "round";
//context.lineCap = "square";
Possible line
context.lineJoin = "miter";
//context.lineJoin = "bevel";
//context.lineJoin = "round";
Shadows
/**
* Shadow attributes on Canvas
* - shadowColor
* - shadowOffsetX
* - shadowOffsetY
* - shadowBlue
*/
context.beginPath();
context.strokeStyle = "red";
context.lineWidth = 7;
context.lineCap = "square";
context.moveTo(200, 100);
context.lineTo(250, 100);
context.shadowColor = "black";
context.shadowOffsetX = 10;
context.shadowOffsetY = 10;
context.shadowBlur = 5;
context.stroke();