HTML Canvas Explained: An Intro to HTML5 Canvas and JavaScript Functions
The HTML5 canvas element has opened up a world of possibilities for drawing and animating graphics using JavaScript. In this article, we‘ll take an introductory look at the canvas API and see how we can use it in combination with JavaScript functions to create visual masterpieces in the browser.
What is the HTML5 Canvas?
At its core, the canvas element is a bitmap drawing surface that allows you to draw graphics and animations using JavaScript. It was first introduced by Apple for use in their Safari web browser, and was later adopted as part of the HTML5 specification.
The canvas element itself is very simple, consisting of a drawable region defined by a width and height. JavaScript is used to actually draw and manipulate the contents of the canvas. Here‘s a basic example of a canvas element:
<canvas id="myCanvas" width="500" height="500"></canvas>
One of the key advantages of the canvas API is that it‘s resolution dependent. This means the canvas will look crisp and sharp on high DPI screens, making it well-suited for the modern web.
The Canvas Drawing Context
Before we can start drawing on our canvas, we first need to grab a reference to the rendering context. The canvas API provides a getContext() method for obtaining the drawing context. We‘ll be working with a 2D rendering context in this article, but it‘s worth noting that there is also a 3D context called WebGL.
To get the 2D rendering context:
let canvas = document.getElementById(‘myCanvas‘);
let context = canvas.getContext(‘2d‘);
The context object contains all the methods and properties we need for drawing on the canvas. With our canvas and rendering context ready, let‘s look at how to draw some basic shapes.
Drawing Shapes on the Canvas
The canvas grid or coordinate space uses a standard Cartesian coordinate system, with the origin (0,0) located at the top-left corner. The x-coordinates increase to the right, while the y-coordinates increase downward.
Drawing Rectangles
The fillRect() method allows us to draw a filled rectangle on the canvas. It takes the x, y coordinates of the top-left corner, and the rectangle‘s width and height as arguments.
context.fillRect(10, 10, 100, 100);
This will draw a 100×100 pixel black square on the canvas. If we want to draw an outline instead of a filled rectangle, we can use the strokeRect() method.
Drawing Paths
The canvas API provides a number of methods for drawing paths, which are essentially a list of points connected by lines. To create a path:
- Call the beginPath() method to start a new path
- Use moveTo(), lineTo() and other methods to draw the path
- Call stroke() or fill() to render the path on the canvas
Here‘s an example of drawing a simple triangle path:
context.beginPath();
context.moveTo(125, 125);
context.lineTo(100, 75);
context.lineTo(150, 75);
context.closePath();
context.stroke();
The moveTo() method moves the drawing cursor to the specified coordinates, while lineTo() draws a line from the current drawing position to the specified position. The closePath() method draws a straight line back to the start of the path.
Drawing Arcs and Circles
To draw arcs or circles, we can use the arc() method. It takes the following parameters:
- x and y coordinates of the center
- radius
- start angle and end angle (in radians)
- counterclockwise (optional boolean)
To convert degrees to radians, we can use the following JavaScript expression:
radians = (Math.PI/180)*degrees
For example, to draw a complete circle:
context.beginPath();
context.arc(250, 250, 100, 0, 2 * Math.PI);
context.stroke();
This will draw the outline of a circle with a radius of 100 pixels in the center of a 500×500 pixel canvas.
Applying Colors and Styles
The canvas API gives us a lot of flexibility for styling the shapes and paths we draw. We can apply colors, gradients, line styles, shadows, and more.
Colors
To set the fill color, we use the fillStyle property. For the outline, we use strokeStyle.
context.fillStyle = ‘red‘;
context.strokeStyle = ‘blue‘;
Both properties accept any valid CSS color value, such as named colors, hex values, rgb() or hsla().
Gradients
We can also fill and stroke shapes with gradient colors using the createLinearGradient() or createRadialGradient() methods.
let gradient = context.createLinearGradient(0, 0, 500, 0);
gradient.addColorStop(0, ‘green‘);
gradient.addColorStop(1, ‘white‘);
context.fillStyle = gradient;
context.fillRect(0, 0, 500, 500);
This creates a linear gradient that goes from green to white, and applies it to a filled rectangle that covers the entire canvas.
Patterns
To use an image as a repeating fill pattern, we can create a pattern using the createPattern() method.
let img = document.getElementById(‘myImage‘);
let pattern = context.createPattern(img, ‘repeat‘);
context.fillStyle = pattern;
context.fillRect(0, 0, 500, 500);
This fills the canvas with a tiled pattern using the specified image. The second argument to createPattern() specifies how the image is repeated – valid values are ‘repeat‘, ‘repeat-x‘, ‘repeat-y‘, and ‘no-repeat‘.
Drawing Text
The canvas API also includes functions for drawing text. The most basic method is fillText(), which draws filled-in text on the canvas.
context.font = ‘40px Arial‘;
context.fillText(‘Hello World!‘, 50, 100);
We use the font property to specify the font size and family, then call fillText() with the text and x/y coordinates for the bottom-left corner of the text. To get the outline of the text, we can substitute strokeText() instead.
Animating the Canvas
Since the canvas is a bitmap, if we want to update the drawing, we need to clear it and redraw the contents for every frame. We can use setInterval() or requestAnimationFrame() to control the animation loop.
Here‘s a basic example of a bouncing ball using setInterval():
let x = 250;
let y = 250;
let xSpeed = 2;
let ySpeed = 2;
function drawBall() {
context.beginPath();
context.arc(x, y, 10, 0, Math.PI*2);
context.fillStyle = ‘red‘;
context.fill();
context.closePath();
}
function update() {
context.clearRect(0, 0, 500, 500);
drawBall();
if(x + 10 > 500 || x - 10 < 0) {
xSpeed = -xSpeed;
}
if(y + 10 > 500 || y - 10 < 0) {
ySpeed = -ySpeed;
}
x += xSpeed;
y += ySpeed;
}
setInterval(update, 10);
For each animation frame, we clear the canvas, redraw the ball at its new position, and update the x and y values based on the speed. Checking the bounds makes the ball appear to bounce off the edges of the canvas.
Canvas Best Practices
Here are a few tips and best practices to keep in mind when working with the canvas API:
- Batch canvas calls together using paths and draw all the paths at once for better performance
- Avoid unnecessary canvas state changes by grouping fills and strokes with the same style
- Use multiple layered canvases to improve perceived performance for complex drawings
- Leverage CSS for border and background colors instead of drawing them on the canvas
- Ensure canvas has the appropriate resolution to look sharp on high DPI displays
Canvas Exercises
To test your canvas skills, try creating the following:
- An animated stick figure character
- An analog clock face with moving hands
- An interactive drawing app using mouse events
- A basic side-scrolling game with keyboard controls
Share your creations and discoveries in the comments below!
Conclusion
The HTML5 canvas element provides a powerful API for creating 2D graphics and animations natively in the browser. When combined with JavaScript functions, the creative possibilities are nearly endless.
In this article, we covered the basics of setting up a canvas, applying styles and colors, drawing shapes and paths, animating the canvas, and more. I hope this has inspired you to dive in and start experimenting with the canvas API on your own. Happy drawing!