Getting Started with <canvas>

To draw with canvas, add the canvas element to the HTML and use JavaScript to access its drawing context.

The canvas Element

The canvas element requires an id so you can find it using JavaScript:

Width and Height

It is important to set the width and height attributes directly on the element. If you use CSS to set the size, the canvas might look "stretched" because the internal coordinate system defaults to 300x150 pixels regardless of the CSS size.

Accessing the Context

The <canvas> element itself is just a container. To actually draw something, you need to use JavaScript to get the rendering context.

Most common usage involves the "2d" context, which provides methods for drawing shapes, text, and images:

A Simple Example

Combining the HTML and JavaScript, here is a complete example that draws a simple blue rectangle:

View Output

Next Steps

Now that you have your canvas set up and ready to go, the next lesson will show you how to draw various types of rectangles.