A Guide to HTML Canvas
Understanding HTML Canvas
You can use canvas to draw boxes, paths, and text, and to add images to a webpage. Developers can also make the illustrations created using canvas interactive so they can be used for animation, data visualization, infographics, and games.
Getting Started with Canvas
To get started with canvas you need to create a skeleton HTML page first, give it a name, and save it somewhere memorable. Next, go between the two body tags, indicated by <body> at the start and </body > at the end, and add <canvas>. You have just created your first canvas element, although it does not do anything just yet.
Your element should now look something like this: <canvas id=”my-canvas” width=”500″ height=”500″></canvas>.
We then need to add the rendering context. This will specify how we can draw inside the canvas. Because we will be drawing in 2D, the code will look like this: “let context = canvas.getContext(‘2d’);. Add this line below the line reference code we write above.
Drawing Within the Canvas
To keep things simple, we will be drawing a line. To do this, we will need to understand coordinates. A canvas is two-dimensional, meaning all pixels in it can be referenced using X/Y coordinates, with the minimum for each coordinate being 0 and the maximum being the values set for the width and height respectively.
To draw a line, we use the moveTo() method that indicates where the line starts, the lineTo() method for where the line ends, and stroke() to draw the line.
There are many other methods you can use to draw different shapes. All of these are provided within the reference resources like Mozilla MDN, where you can learn even more about the <canvas> element.
Although we have looked at the basics of using the canvas element, there is a lot more you can do with it, especially when you look further into its specs on available reference resources.