In this lesson, you'll learn how to draw a rectangle on a JavaScript canvas. You will discover how to create it from scratch and how to play around with sizes and colors.
This lesson is part of a module on the JavaScript Canvas API and other JavaScript concepts. For the first lesson in this module, please see JavaScript Canvas API Introduction.
Set Up the Canvas
The first things you'll draw are rectangles. Here is the code you should have so far:
HTML:
<!-- basics.html -->
<!-- ... -->
<body>
<canvas id="canvas"></canvas>
</body>
<!-- ... -->
JavaScript:
// basics.js
const canvas = document.getElementById('canvas');
[canvas.width, canvas.height] = [300, 300];
const context = canvas.getContext('2d');
Color and Style Your Rectangle
All the methods for drawing are in the CanvasRenderingContext2D which you've instantiated and assigned to the context variable. The first step is to define what color to draw in. This is like selecting the colored pencil you are going to use before actually drawing:
// basics.js
// ...
context.fillStyle = 'rgb(200, 0, 0)'; // red
Here you are setting the .fillStyle property of the CanvasRenderingContext2D to a string. This string can be any valid CSS color string. For example, 'blue', '#094089', and 'rgba(200,0,0,1)' are all color strings that work here.
With the color selected, it's time to fill a rectangle:
// basics.js
// ...
context.fillStyle = 'rgb(200, 0, 0)';
context.fillRect(10, 10, 280, 280); // starting x, starting y, width, height
Here you call the .fillRect() method of the CanvasRenderingContext2D. This method takes four arguments:
- Starting
xposition - Starting
yposition widthof rectangleheightof rectangle
This will fill a large red rectangle that almost fills the entire canvas.
Note how first a color was selected and then a drawing instruction was made. This is how operations are generally done with the canvas.
You can select a color and then draw a bunch of rectangles without having to specify the color each time. However, if you want to draw multi-colored rectangles, you'd have to select the color before each .fillRect() command.
If you go to the console where your canvas is rendered and type console.dir(context) you'll see all the attributes that belong to the CanvasRenderingContext2D. This is your drawing tool. It has certain attributes, like color, thickness, shadow and style amongst others. To draw in a certain way, you define certain parameters of the tool and then instruct it to draw on certain coordinates.
Other Ways to Draw or Remove a Rectangle
There are other methods you can use to draw, or remove rectangles.
Add to this a few new context methods calls to .clearRect() and .strokeRect():
// basics.js
// ...
context.clearRect(50, 50, 50, 50);
context.strokeRect(100, 100, 50, 50);
context.strokeRect(110, 110, 50, 50);
context.strokeRect(120, 120, 50, 50);
The .clearRect() method clears a rectangular area from the canvas, making it transparent. The .strokeRect() method draws the outline of a rectangle. "Stroke" is the word often used to describe outlines, used especially in vector graphics. These methods have the same arguments as fillRect.
With that, you should see something like this:
Looking nice!
The default line width is 1 pixel. You can set the line width by setting the .lineWidth property of the CanvasRenderingContext2D:
context.lineWidth = 5;
Now, if you draw another .strokeRect() you'll see that the line is thicker.
Tips to Navigate Canvas API Documentation
For other methods to manipulate lines, check out the reference documentation on MDN.
Your abilities at navigating documentation are key. Once you unlock the ability to read, draw conclusions, and write code from documentation, is when you start to become an independent and creative coder. No coder alive is free from documentation!
It must be noted that the API itself may not seem 100% consistent. For .lineWidth for example, you can get and set the values directly as shown above.
However, for the line dash property, the pattern of the line, you need to call a specific getter and setter, .getLineDash() and .setLineDash(). There are other properties too that can be assigned directly and others for which you need to call the appropriate getter or setter, bear this in mind, and double check the documentation!
The reason for getters and setters for some attributes is generally because they may need to set more than one value. For example, the .setLineDash() method takes an array of numbers, which represent the length of the dashes and the length of the gaps between them.
Also, watch out for the fact that there are some methods relating to lines that have line in the name, and others that have stroke. Stroke usually refers to outlines of shapes, yet the boundary between a line and a stroke is quite blurry (pun not intended!) You also have paths, to confuse you further! Broadly speaking:
- A Path is a series of points that can be connected with lines or curves
- A Line is a straight path
- A Stroke is the outline of a shape
That said, the terminology can overlap, so it's best to just get used to it and not worry too much about it. Learn by experimentation!
Learn by Doing
If you're following along with the project, get the examples from this lesson and get them working in your labs repository. Make a few variations, too.
If you're doing this course step-by-step, and especially if you're in the mentorship program, please be sure to push your work to GitHub when you're done.
Summary: Draw a Canvas Rectangle
- How to draw a Canvas rectangle:
- Create a canvas element in your HTML
- Use JavaScript to assign a height and a width
- Set the fill color using the
.fillStylemethod
- Familiarize yourself with the reference documentation on MDN