The canvas element
The canvas element creates a drawable area; JavaScript supplies the pixels and the drawing commands.
What you will learn
- How to declare a canvas and provide fallback text
- Why the width and height attributes matter
- How CSS sizing differs from the drawing buffer
Basic markup
<canvas id="scene" width="320" height="180">
A simple scene is displayed here.
</canvas>The attributes define the internal drawing surface. CSS can control the displayed size, but stretching the surface without considering its ratio can make the result blurry.
Start drawing
const canvas = document.querySelector('#scene');
const context = canvas.getContext('2d');
context.fillStyle = '#2463eb';
context.fillRect(20, 20, 100, 60);Common mistakes
- Do not omit useful fallback content for users who cannot see the drawing.
- Do not use Canvas for text, forms, or controls when semantic HTML is more suitable.
- Check that a context exists before calling drawing methods.
- Keep important information available outside the pixels.