How to Draw a Rectangle with JavaScript and HTML5 Canvas

2021-01-15 14:33:32 | #programming #javascript #html5 #canvas

Tested On

  • Linux Ubuntu 20.04
  • Windows 10
  • macOS Catalina

The Canvas element was first introduced to various browsers in 2004, by Apple, and heavily promoted along with HTML5. Canvas itself is just an HTML element, though. You still have to use JavaScript and the Canvas API to draw graphics to the screen. So why render a box within a Canvas container when you could just render with HTML and CSS?

Canvas is more optimized for rendering thousands of objects, where HTML divs are clunky and don't scale as well. That's why we're going to learn not just how to create a rectangle, but also a Rectangle class, which will make it easy to instantiate multiple instances of rectangles. Or squares, for that matter.

Canvas can even leverage your GPU for hardware-accelerated features, draw pseudo-3D and full 3D. Granted, so can HTML and CSS. One big drawback to using canvas, however, is that the items drawn to the container are rasterized, meaning they have slightly pixelated edges unless you employ some sort of anti-aliasing.Most HTML elements, on the other hand, are crisp at whatever size.

The following program demonstrates how to draw a rectangle with a custom Rectangle class. Try modifying the code below, to change the position, dimensions, and fill color of the shape. And see if you can figure out how to render multiple rectangles to the Canvas. Then, skip to the next section for a detailed explanation.

Code Editor

The HTML5 Canvas Coordinate System

The image below depicts a standard two-dimensional coordinate system, with the origin (0, 0) at the center. The x-axis is horizontal along the center with negative x going off to the left, and positive x going off to the right. The y-axis is vertical along the center with negative y going off to the bottom, and positive y going off to the top.

Canvas, however, has its origin at the top left. The x-axis still increases positively to the right, but y is reversed, going positively towards the bottom of the screen. Here's an example of a rectangle's coordinates, if we were to render it within Canvas.

Explanation of the HTML5 Canvas Rectangle Code

Now that we have a good understanding of rectangles and the Canvas coordinate system, we can get back to coding them.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var Rectangle = function(x, y, width, height, fillStyle) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
  this.fillStyle = fillStyle;

  this.render = function(ctx) {
    ctx.beginPath();
    ctx.rect(this.x, this.y, this.width, this.height);
    ctx.fillStyle = this.fillStyle;
    ctx.fill();
  }
}

var rectangle = new Rectangle(20, 20, 100, 50, '#2793ef');
rectangle.x = 50;
rectangle.render(ctx);

Lines 1-2: Store an instance of the Canvas and Canvas context so they can be easier to reference later on.

Line 4: Define a Rectangle class, and five key parameters for the sizing, positioning, and coloring of our shape.

Lines 5-8: Store the parameters into instance variables. This makes it so each instance of a rectangle has its own properties that we can define and update without impacting the other rectangle instances on the stage.

Lines 11-16: The render() function, when invoked, draws the shape to the canvas. ctx.beginPath() tells Canvas to begin drawing a path, which we do so with the ctx.arc() method. This method accepts the following parameters, in the order you see them on line 12:

Parameter Description
x The position of the rectangle on the x-axis
y The position of the rectangle on the y-axis
width The width of the rect
height The height of the rect

Lines 14-15: Defines fill properties and invokes the ctx.fill() command to fill in the shape.

Lines 19-21: Instantiates the rectangle and renders it to the canvas.

How to Draw Squares with JavaScript and HTML5 Canvas

To draw a square, instead of a rectangle, just make sure the width and height are equal, like so:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var rectangle = new Rectangle(20, 20, 100, 100, '#2793ef');
rectangle.render(ctx);

Drawing Multiple Rectangles to Canvas with a JavaScript Loop

This loop draws rectangles in a staggered, stairstep fashion. Feel free to adjust the count and experiment with position and size variations.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var rectangles = [];
for (var i = 1; i <= 10; i++) {
  var r = new Rectangle(20 * i, 20 * i, 20, 20, '#2793ef');
  r.render(ctx);
  rectangles.push(r);
)

rectangles[9].x = 0;

Conclusion

In this tutorial, we learned about the basic components of a rectangle and how it is measured. We also learned how to invoke the Canvas API with native JavaScript to render a rectangle to the screen, and how easy it is to make multiple rectangles with a Circle class.

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.



Hire Us for IT and Consulting Services









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Services

We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

We Noticed Adblock Running

Because we offer a variety of free programming tools and resources to our visitors, we rely on ad revenue to keep our servers up. Would you consider disabling Adblock for our site and clicking the "Refresh Page" button?

Contact