Summary: in this tutorial, you’ll learn about HTML Canvas and how to use JavaScript to draw on the canvas.
Introduction to the HTML5 Canvas element
HTML5 features the <canvas> element that allows you to draw 2D graphics using JavaScript.
The <canvas> element requires at least two attributes: width and height that specify the size of the canvas:
<canvas width="500" height="300" id="canvas"></canvas>Code language: HTML, XML (xml)Like other elements, you can access the width and height properties of the <canvas> element via its DOM properties:
const canvas = document.querySelector('#canvas');
const width = canvas.width;// 500
const height = canvas.height;// 300Code language: JavaScript (javascript)And you can also change the width and height of the <canvas> element using the DOM methods:
canvas.width = 600;
canvas.height = 400;Fallback content
Unlike the <img> element, The <canvas> element requires the closing tag </canvas>. Any content between the opening and closing tags is fallback content that will display only if the browser doesn’t support the <canvas> element. For example:
<canvas width="500" height="300" id="canvas">The browser doesn't support the canvas element</canvas>Code language: HTML, XML (xml)Nowadays, most modern web browsers support the <canvas> element.
The rendering context
Initially, the canvas is blank. To draw something, you need to access the rendering context and use it to draw on the canvas.
The <canvas> element features the getContext() method that returns a render context object.
The getContext() takes one argument which is the type of context. For example, you use the "2d" to get a 2D rendering context object, which is an instance of the CanvasRenderingContext2D interface.
The 2D rendering context allows you to draw shapes, text, images, and other objects.
The following example shows how to select the canvas element using the querySelector() method and access the drawing context by calling its getContext() method:
let canvas = document.querySelector('#canvas');
let ctx = main.getContext('2d');Code language: JavaScript (javascript)Check for canvas support
When using the <canvas> element, it’s important to check if the browser supports the getContext() method. To do it, you use the following code:
let canvas = document.querySelector('#main');
if(canvas.getContext) {
let ctx = main.getContext('2d');
}Code language: JavaScript (javascript)The 2D context
The 2D drawing context features methods for drawing simple 2D shapes such as paths, rectangles, and arcs.
The coordinates in a 2D context begin at the upper-left of the <canvas> element, which is point (0,0) as shown in the following picture: