How to Create Canvas in HTML: Simple Guide with Examples
To create a canvas in HTML, use the
<canvas> element with optional width and height attributes. This element acts as a drawing area where you can use JavaScript to draw shapes, images, and animations.Syntax
The basic syntax to create a canvas is using the <canvas> tag with optional width and height attributes to set its size in pixels. If you don't set these, the default size is 300 pixels wide and 150 pixels tall.
- <canvas>: The HTML element that creates the drawing area.
- width: The width of the canvas in pixels.
- height: The height of the canvas in pixels.
html
<canvas id="myCanvas" width="400" height="200"></canvas>
Output
A blank rectangular area 400 pixels wide and 200 pixels tall appears on the page.
Example
This example shows how to create a canvas and draw a red rectangle on it using JavaScript. The canvas is 300 pixels wide and 150 pixels tall.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas Example</title> </head> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #000000;"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'red'; ctx.fillRect(50, 40, 100, 60); </script> </body> </html>
Output
A 300x150 pixel canvas with a black border showing a solid red rectangle starting 50 pixels from the left and 40 pixels from the top, sized 100x60 pixels.
Common Pitfalls
Some common mistakes when creating a canvas include:
- Not setting
widthandheightattributes on the<canvas>tag, which can cause unexpected default sizes. - Using CSS to set the size without matching the canvas attributes, which can stretch or blur the drawing.
- Forgetting to get the 2D context with
getContext('2d')before drawing.
html
<!-- Wrong: CSS size only --> <canvas id="wrongCanvas" style="width:400px; height:200px; border:1px solid black;"></canvas> <!-- Right: Set attributes and CSS --> <canvas id="rightCanvas" width="400" height="200" style="border:1px solid black;"></canvas>
Output
The first canvas may appear stretched or blurry because its internal drawing size is default 300x150 but CSS sets it to 400x200. The second canvas matches internal size and CSS size, so it looks sharp.
Quick Reference
Remember these key points when working with canvas:
- Use
<canvas width="..." height="...">to set size. - Use JavaScript's
getContext('2d')to draw. - Match CSS size with canvas attributes to avoid distortion.
- Canvas is a pixel-based drawing surface, not a container for HTML elements.
Key Takeaways
Use the
Always get the 2D context in JavaScript before drawing on the canvas.
Set canvas size with attributes, not just CSS, to keep drawings sharp.
Canvas is for pixel drawing, not for placing HTML content inside.
A border style helps visually see the canvas area during development.