Dynamic canvas
We can draw more advanced shapes, add images, and add text. This enables us to take our canvas skills to the next level.
Adding lines and circles to the canvas
Here we will see how to draw a line and a circle. Here is a piece of sample code that draws a line:
<!DOCTYPE html>
<html>
<head>
<style>
#canvas1 {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas1"></canvas>
<script>
let canvas = document.getElementById("canvas1");
let ctx = canvas.getContext("2d");
canvas.width = 100;
canvas.height = 100;
ctx.lineWidth = 2;
ctx.moveTo(0, 20);
ctx.lineTo(50, 100);
ctx.stroke();
</script>
</body>
</html>
The line width is set to 2
pixels. This first puts the focus to 0
(x) and 20
(y). This means it is at the very left edge of the canvas...