JavaScript > Browser APIs > Canvas API > Drawing shapes

Drawing a Rectangle with Canvas API

This code snippet demonstrates how to draw a rectangle on an HTML canvas using the Canvas API in JavaScript. We'll explore setting up the canvas, defining the rectangle's properties (position, size, color), and then drawing it using the `fillRect` method.

Setting up the Canvas

First, we retrieve the HTML canvas element using `document.getElementById`. It's crucial to have a canvas element defined in your HTML with the ID 'myCanvas'. Then, we obtain the 2D rendering context using `canvas.getContext('2d')`. This context provides the methods for drawing shapes, text, and images onto the canvas. Finally, we explicitly set the width and height of the canvas element. It is recommended to set the width and height attributes in the javascript code instead of the css code.

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

canvas.width = 400; // Set canvas width
canvas.height = 200; // Set canvas height

Defining Rectangle Properties

Here, we define the properties of our rectangle. `rectX` and `rectY` specify the position of the top-left corner of the rectangle on the canvas. `rectWidth` and `rectHeight` define the dimensions of the rectangle. `rectColor` sets the fill color for the rectangle; you can use any valid CSS color value (e.g., color names, hexadecimal codes, RGB values).

const rectX = 50; // X-coordinate of the top-left corner
const rectY = 50; // Y-coordinate of the top-left corner
const rectWidth = 200; // Width of the rectangle
const rectHeight = 100; // Height of the rectangle
const rectColor = 'skyblue'; // Color of the rectangle

Drawing the Rectangle

Before drawing, we set the `fillStyle` property of the canvas context to the desired color for the rectangle. Then, we use the `fillRect` method to draw a filled rectangle. `fillRect` takes four arguments: the x-coordinate of the top-left corner, the y-coordinate of the top-left corner, the width, and the height.

ctx.fillStyle = rectColor; // Set the fill color
ctx.fillRect(rectX, rectY, rectWidth, rectHeight); // Draw the filled rectangle

Complete Code Example

This is the complete code, you can copy and paste into your project and see the rectangle on your HTML page.

<canvas id="myCanvas"></canvas>
<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');

  canvas.width = 400;
  canvas.height = 200;

  const rectX = 50;
  const rectY = 50;
  const rectWidth = 200;
  const rectHeight = 100;
  const rectColor = 'skyblue';

  ctx.fillStyle = rectColor;
  ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
</script>

Concepts Behind the Snippet

This snippet demonstrates fundamental concepts of the Canvas API: accessing the canvas element, obtaining the 2D rendering context, setting properties like fill color, and using methods like `fillRect` to draw shapes. Understanding these core concepts is crucial for creating more complex canvas-based graphics and animations.

Real-Life Use Case

Drawing rectangles is a basic building block for many canvas applications. It can be used for creating simple games (e.g., drawing paddles and the ball in a Pong game), data visualizations (e.g., creating bar charts), UI elements (e.g., drawing buttons and boxes), and image editing tools (e.g., creating selection rectangles).

Best Practices

  • Set canvas dimensions using JavaScript: Setting `canvas.width` and `canvas.height` in JavaScript is the best practice. Setting dimensions via CSS can lead to scaling issues and blurry rendering.
  • Understand the coordinate system: The origin (0, 0) is at the top-left corner of the canvas. The x-axis increases to the right, and the y-axis increases downward.
  • Use descriptive variable names: Using clear and descriptive variable names like `rectX`, `rectY`, `rectWidth`, and `rectHeight` makes the code more readable and maintainable.

Interview Tip

Be prepared to explain the basic steps involved in drawing shapes on a canvas: getting the context, setting properties, and using drawing methods. Also, understand the difference between `fillRect`, `strokeRect` and `rect`.

When to Use Them

Use the Canvas API when you need to create dynamic and interactive graphics in the browser. It's particularly well-suited for games, data visualizations, animations, and image editing tools.

Memory footprint

The memory footprint of canvas operations depends on the size of the canvas and the complexity of the drawings. Simple shapes like rectangles have a relatively low memory impact. However, complex drawings with many objects, gradients, and shadows can consume more memory. Optimizing your code to reduce the number of drawn elements and minimize the use of computationally expensive effects can help improve performance and reduce memory usage.

Alternatives

Alternatives to the Canvas API include SVG (Scalable Vector Graphics) and WebGL. SVG is a vector-based format that is well-suited for creating scalable graphics and animations. WebGL is a more advanced API for rendering 2D and 3D graphics using the GPU.

Pros

  • Pixel-level control: The Canvas API provides fine-grained control over individual pixels, allowing for highly customized graphics.
  • Performance: For complex scenes with many objects, canvas can be faster than SVG, especially for raster-based operations.

Cons

  • Resolution dependent: Canvas graphics are rasterized, meaning they can become blurry when scaled up.
  • No DOM elements: Unlike SVG, canvas elements are not part of the DOM, making it more difficult to manipulate individual objects after they have been drawn.

FAQ

  • Why does my rectangle not appear?

    Make sure you have an HTML canvas element with the correct ID ('myCanvas') in your HTML. Also, double-check that you've set the `width` and `height` of the canvas using JavaScript, not just CSS. Finally, verify that the `rectColor` is a valid CSS color value.
  • How can I draw a rectangle with a border instead of a filled rectangle?

    Instead of `fillRect`, use `strokeRect`. You'll also need to set the `strokeStyle` property of the canvas context to specify the border color and the `lineWidth` property to set the border thickness.
  • How do I make the rectangle transparent?

    You can use the `globalAlpha` property of the canvas context. Set it to a value between 0 (fully transparent) and 1 (fully opaque) before drawing the rectangle. For example, `ctx.globalAlpha = 0.5;` will make the rectangle 50% transparent.