HTML5 Canvas line and rectangles

<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>
#c1 {
border: 1px solid;
display: block;
width: 600px;
height: 300px;
margin: 0 auto;
}
Canvas with border

Let’s try to add a few basic primitives

//Definitions
let canvas = document.getElementById('c1');
let context = canvas.getContext("2d");

Canvas Rectangle

//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

//Draw line
context.beginPath();
context.strokeStyle = "white";
context.lineWidth = 4;
context.moveTo(20, 20);
context.lineTo(30, 50);
context.stroke();
Canvas with a Line
context.lineCap = "butt";
//context.lineCap = "round";
//context.lineCap = "square";
Possible line cap
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

Thank you for your attention.

Senior web developer, architect, cryptocurrencies trader, https://lytvynov-anton.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store