What is Canvas?#
Apple first introduced Canvas in 2004 to enhance applications and the Safari browser. Later, the WHATWGWeb Hypertext Application Technology Working Group standardized it. Canvas offers fine-grained control over rendering, but this comes with the responsibility of manually managing every detail. Essentially, it can handle numerous objects, but we need to code everything explicitly.
The canvas uses a 2D drawing context for rendering shapes, text, images, and other objects. The process is similar to choosing a color and brush before painting. We can change these attributes before each new drawing or continue with the existing ones.
Canvas offers fine-grained control over rendering, but this comes with the responsibility of managing every detail manually. It’s a “fire-and-forget” system—once you’ve drawn something, it’s remembered as pixels, not as an object you can directly manipulate. So, if you want to move an object, you need to redraw it in a new position.
Animating on Canvas is similar to creating a stop-motion film. Each frame requires subtly shifting the objects to create the illusion of movement.
The <canvas> element#
The HTML <canvas>
element is an HTML5 tag that provides a blank container on which we can draw graphics. We can draw shapes and lines using the anvas API, which facilitates graphic rendering via JavaScript. Unlike SVG, which is vector-based, canvas works with pixels, making it more suitable for complex graphics and animations.
A canvas is a rectangular area on an HTML page that, by default, lacks a border or content. Its default width size is 300 pixels, and its height size is 150 pixels, but we can customize this using the HTML height
and width
properties: