The HTML <canvas> element is only a container for graphics.
Canvas has several methods for drawing paths, boxes, circles, text and for adding images.
<canvas width='150' height='150'></canvas>
<script src="canvas.js"></script>
The <canvas> element has a method called .getContext() used to access drawing functions
const canvas = document.querySelector('canvas');
let c = canvas.getContext('2d');
c.fillRect(10, 10, 100, 100);
c.fillStyle = 'green';
The canvas has a default grid overlay, normally 1 unit in the grid cooresponds to 1 pixel on the canvas.
The position of each drawn item will be translate it's (x, y) coordinates to different posoitions on the grid.
Rectangles
fillRect(x, y, width, height
Draws a filled rectangle.
Parameters x and y specify the position on the canvas, width and height provide the rectangle's size.
Paths
A path is a list of points, connected by segments of lines that can be curved, and have different widths and colors.
To make a shape using paths:
- Create the path.
- Use drawing commands to draw into the path.
- Close the path.
- Stroke or fill the path to render it.
c.beginPath() initializes the path.
moveTo(x, y) function to place the starting point.
lineTo(x, y) draws a line from the current position to the specified x and y postion.
The starting point is dependent on previously drawn paths, where the end point of the previous path is the starting point for the following, etc.
Arcs/Cirlces
Use the arc method
arc(x, y, radius, startAngle, endAnge, anticlockwise)
Draws an arc which is centered at (x,Y) with radius starting at startAngle and ending at endAngle going in the given direction.
fillStyle = color
Sets the style used when filling shapes
strokeStyle = color
Sets the style for shapes outlines
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial
https://codepen.io/pen/?editors=1010
https://codepen.io/NrupM/pen/QqLwMN