Skip to content

Canvas Drawing

All drawing operations on an HTML <canvas> element are performed using JavaScript. The canvas itself is just a blank drawing surface; JavaScript provides the tools to bring it to life.

Here’s a basic example of drawing a red rectangle:

// HTML needed: <canvas id="myCanvas" width="200" height="100"></canvas>
// JavaScript (ideally placed after the canvas element in HTML or in a DOMContentLoaded event listener)
const canvas = document.getElementById('myCanvas');
// Check if the canvas element and getContext are supported
if (canvas && canvas.getContext) {
const ctx = canvas.getContext('2d'); // Get the 2D rendering context
// Set the fill color
ctx.fillStyle = 'red'; // You can use color names, hex codes (#FF0000), rgb(), etc.
// Draw a filled rectangle
// fillRect(x, y, width, height)
ctx.fillRect(10, 10, 150, 75); // x, y, width, height
} else {
console.error('Canvas not supported or element not found.');
}

First, you need to get a reference to the <canvas> element in your HTML document. This is typically done using its id attribute with the document.getElementById() method.

const canvas = document.getElementById('myCanvas');

It’s good practice to ensure your script runs after the HTML element has been loaded by the browser, for example, by placing your <script> tag just before the closing </body> tag, or by using an event listener like DOMContentLoaded.

Step 2: Create a Drawing Object (Rendering Context)

Section titled “Step 2: Create a Drawing Object (Rendering Context)”

Once you have the canvas element, you need to get its drawing context. The context is an object that provides all the necessary methods and properties for drawing on the canvas.

The most common context is the 2D rendering context, obtained by calling the getContext('2d') method on the canvas element.

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

It’s advisable to check if canvas.getContext is available to handle browsers that might not support canvas (though this is rare today).

With the rendering context (ctx), you can now start drawing. For example, to draw a filled rectangle:

  1. Set the fill style (color, gradient, or pattern):
ctx.fillStyle = '#FF0000'; // Sets the fill color to red

The fillStyle property can be any valid CSS color string (e.g., ‘blue’, ‘#00FF00’, ‘rgb(0, 0, 255)’), a gradient object, or a pattern object. The default fillStyle is black (#000000).

  1. Draw the filled rectangle using fillRect():
ctx.fillRect(x, y, width, height);
  • x: The x-coordinate of the upper-left corner of the rectangle.
  • y: The y-coordinate of the upper-left corner of the rectangle.
  • width: The width of the rectangle.
  • height: The height of the rectangle.

Example:

ctx.fillRect(0, 0, 150, 75); // Draws a 150x75 pixel red rectangle at the top-left corner of the canvas.

This is just the beginning! The 2D context offers many more methods for drawing paths, lines, arcs, text, images, and applying transformations.