How to Create Graphics with JavaScript Canvas

Remember when we talked about HTML and CSS, we briefly introduced something called SVG. It allows us to create vector images by simply using an XML structure.

In this lesson, we are going to discuss something similar called canvas, except it allows us to use JavaScript to create graphics on web pages. And because it uses a programming language instead of a simple markup language, that makes canvas much more flexible compared to SVG.

We know that the SVG has a DOM tree structure, and the shape, color, and position are all represented using tags and attributes.

The canvas, however, is a single node in the DOM tree. It encapsulates a space on the web page, where you can create vector images using JavaScript. This space can be defined using the <canvas> tag. Here is an example where we create a simple rectangle inside the canvas:

javascript
1<canvas width="300px" height="200px"></canvas>
javascript
1let canvas = document.querySelector("canvas");
2let context = canvas.getContext("2d");
3
4// Define the color of the rectangle
5context.fillStyle = "red";
6
7// The first two parameters put the top left corner of the rectangle at coordinate (10, 10)
8// The last two parameters define the width and height of the rectangle in pixels
9context.fillRect(10, 10, 100, 50);

The getContext() method is used to access the drawing interface, which is like a toolbox where your digital pens and pencils are stored. The parameter 2d stands for two-dimensional graphics.

If you are interested in creating three-dimensional graphics, you should use WebGL instead. But, we are only focusing on the 2D system for now.

Also, notice that we defined the size of the canvas at the beginning. If you don't do that, the canvas element will take a default width of 300 pixels and a height of 150 pixels.

Lines

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉