HTML5 Canvas line and rectangles

Anton Lytvynov
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

Canvas with border

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 & 3 rectangles

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();
Canvas with a Line

Possible line cap

context.lineCap = "butt";
//context.lineCap = "round";
//context.lineCap = "square";
Possible line cap

Possible line

context.lineJoin = "miter";
//context.lineJoin = "bevel";
//context.lineJoin = "round";
Possible left join

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();
Line with a shadow
Shadow with +- combinations of context.shadowOffsetX and context.shadowOffsetY
shadowBlur=10 and shadowBlur=1
context.shadowColor = "green"
Shadow color green

Repository

Tutorial result

You can check the code for this part here.

Thank you for your attention.

Thank you for your attention.

Do you need help with web or mobile development? Feel free to contact me here.

P.S. I really appreciate your like or share 🙏.

--

--

Anton Lytvynov

CEO & Founder of Lytvynov Production, Senior web developer, architect, cryptocurrencies trader, https://lytvynov-production.com