Back to subject
HTML5/HTML Canvas

Draw Your First Shape

Practical lesson

Let's draw a simple shape with the canvas element and JavaScript.

- <canvas> creates a drawing surface with a width and height. - The canvas itself does not draw anything just because it exists. JavaScript normally creates the drawing. - First, JavaScript gets the canvas element from the page. - Then it asks for a 2D drawing context with getContext("2d"). - The drawing context provides methods such as fillRect for drawing a filled rectangle. - The width and height define the canvas coordinate space. - Put useful fallback text inside <canvas> for users or browsers that cannot use the drawing as intended. - Canvas graphics are pixel-based; the drawn pixels are not automatically represented as normal HTML elements.

Read the example in two parts: HTML creates the drawing surface, and JavaScript tells that surface what to draw.

Try it yourself
Code

Starter example

Code
Live preview