Canvas in HTML is used to draw graphics on a web page using JavaScript. The <canvas> element creates a drawable area, but the actual shapes, lines, images, charts, animations, and visual effects are created with script. Canvas is useful when the browser needs to render pixels dynamically instead of showing fixed HTML content.
Canvas is commonly used for games, dashboards, data visualizations, image editing tools, drawing apps, simulations, waveform displays, custom charts, particle effects, and interactive graphics. It is different from normal HTML elements because the browser does not understand individual shapes inside the canvas as separate DOM elements. Once something is drawn, it becomes pixels on a bitmap surface.
Basic Syntax of Canvas in HTML
The canvas element needs width and height. These attributes define the internal drawing surface size. CSS can also resize the canvas visually, but the actual drawing resolution comes from the width and height attributes.
<canvas id="myCanvas" width="500" height="300">
Your browser does not support canvas.
</canvas>
The text inside the canvas is fallback content. It is shown only if the browser does not support canvas. Modern browsers support canvas, but fallback content is still useful for accessibility and older environments.
Getting Canvas Context
To draw on a canvas, JavaScript must get a drawing context. The most common context is 2d, which provides methods for drawing rectangles, lines, circles, text, images, gradients, and paths.
const canvas = document.querySelector("#myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#111160";
ctx.fillRect(50, 40, 180, 100);
This code selects the canvas, gets the 2D drawing context, sets a fill color, and draws a rectangle. The rectangle is not an HTML element. It is drawn as pixels inside the canvas.
Canvas Coordinate System
Canvas uses a coordinate system where the top-left corner is (0, 0). The x value increases from left to right, and the y value increases from top to bottom. If a canvas is 500 pixels wide and 300 pixels tall, the visible drawing area goes from x 0 to 500 and y 0 to 300.
| Coordinate | Meaning |
|---|---|
| x = 0 | Left edge of the canvas |
| y = 0 | Top edge of the canvas |
| x increases | Moves right |
| y increases | Moves down |
| width | Horizontal size of drawing area |
| height | Vertical size of drawing area |
Understanding coordinates is important because every drawing operation depends on positions and sizes. Rectangles, text, lines, and images all need coordinates that tell the browser where to draw.
Drawing Shapes on Canvas
Canvas provides simple methods for rectangles and path-based methods for custom shapes. Rectangles are common for bars, boxes, backgrounds, game objects, and UI overlays.
ctx.fillStyle = "lightblue";
ctx.fillRect(20, 20, 150, 80);
ctx.strokeStyle = "black";
ctx.lineWidth = 3;
ctx.strokeRect(20, 20, 150, 80);
ctx.clearRect(40, 40, 40, 20);
The fillRect() method draws a filled rectangle. The strokeRect() method draws only the border. The clearRect() method clears pixels from a rectangular area.
Drawing Lines and Paths
For lines, triangles, curves, and custom shapes, canvas uses paths. A path starts with beginPath(), moves to a starting point, draws lines or curves, and then fills or strokes the final shape.
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 50);
ctx.lineTo(125, 150);
ctx.closePath();
ctx.fillStyle = "#2c8ffa";
ctx.fill();
This draws a triangle. Paths are flexible and can create icons, graphs, polygons, curves, and custom visual elements. Complex canvas apps are usually built from many repeated path operations.
Drawing Text on Canvas
Canvas can draw text using fillText() and strokeText(). You can set font, color, alignment, and baseline. This is useful for chart labels, game scores, tooltips, and generated images.
ctx.font = "32px Arial";
ctx.fillStyle = "#111160";
ctx.fillText("Canvas in HTML", 40, 80);
Canvas text is also drawn as pixels. It is not selectable like normal HTML text, and it is not naturally available to screen readers. If the text is important content, provide an HTML alternative.
Drawing Images on Canvas
Canvas can draw images using drawImage(). The image must be loaded before drawing. This is used in image editors, games, thumbnails, filters, cropping tools, and export features.
const image = new Image();
image.src = "logo.png";
image.onload = () => {
ctx.drawImage(image, 20, 20, 120, 120);
};
The drawImage method can draw the image at natural size, scale it, or draw only part of it. This makes canvas useful for cropping and image-processing workflows.
Canvas Animation
Canvas animation is usually created by repeatedly clearing and redrawing the canvas. The browser method requestAnimationFrame() is commonly used because it syncs drawing with the browser’s rendering cycle.
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 80, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();
This creates motion by drawing the rectangle at a slightly different x position on every frame. Games and simulations use the same basic idea, but with more state, physics, input handling, and drawing logic.
Canvas Width and CSS Size
Canvas has two sizes: the drawing buffer size and the CSS display size. The width and height attributes control the drawing buffer. CSS controls how large the element appears on the page. If CSS stretches the canvas without matching the internal size, drawings can look blurry.
<canvas id="chart" width="800" height="400"></canvas>
<style>
canvas {
max-width: 100%;
height: auto;
}
</style>
For sharp graphics, choose an appropriate internal resolution. On high-DPI displays, advanced apps often scale the canvas based on devicePixelRatio so drawings remain crisp.
High DPI Canvas Example
On high-DPI screens, one CSS pixel may use more than one physical device pixel. If the canvas drawing buffer is too small, the browser stretches it and the result looks soft. A common solution is to multiply the internal canvas size by the device pixel ratio, then scale the context.
const ratio = window.devicePixelRatio || 1;
const width = 500;
const height = 300;
canvas.width = width * ratio;
canvas.height = height * ratio;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
ctx.scale(ratio, ratio);
After this setup, drawing can still use normal coordinates like 500 by 300, but the internal pixel buffer is sharper. This matters for charts, generated thumbnails, text, and detailed UI graphics.
Exporting Canvas as Image
Canvas can be exported as an image using methods such as toDataURL() or toBlob(). This is useful for drawing apps, certificate generators, chart exports, image editors, and tools that let users download generated graphics.
canvas.toBlob(blob => {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "drawing.png";
link.click();
}, "image/png");
If the canvas uses images from another domain without proper CORS headers, the browser may mark the canvas as tainted. A tainted canvas cannot be exported for security reasons. This protects users from cross-origin image data being read without permission.
Canvas Performance Tips
Canvas can be fast, but inefficient drawing can still cause lag. Avoid redrawing more than necessary. Keep expensive calculations outside the draw loop when possible. Use requestAnimationFrame for animation. Clear only the needed area when that is enough. For very complex scenes, consider layering multiple canvases or using WebGL.
Performance matters most in games, live dashboards, waveform displays, and simulations where the canvas updates many times per second. A static chart or simple generated graphic usually does not need advanced optimization.
Canvas Mouse Interaction
Canvas can respond to mouse or touch input, but you must calculate interaction manually. If the user clicks a drawn rectangle, the browser does not know that a rectangle exists. JavaScript receives the click coordinates, and your code checks whether those coordinates fall inside the shape.
This manual hit testing is one reason canvas is powerful but more work than SVG for element-level interaction. For a drawing app or game, this control is useful. For simple clickable icons or diagrams, SVG may be easier.
Canvas Accessibility
Canvas content is not automatically accessible because the browser sees it as one drawing surface. If the canvas shows important information, provide an accessible alternative using normal HTML, ARIA where appropriate, or text near the canvas.
For a chart, provide a table or summary. For a game, provide keyboard controls and instructions. For generated visual content, describe the output. Canvas should not be the only source of essential information unless you have provided another accessible path.
Canvas vs SVG
| Feature | Canvas | SVG |
|---|---|---|
| Rendering | Bitmap pixels | Vector elements |
| DOM access | No separate DOM for shapes | Each shape can be an element |
| Best for | Games, heavy drawing, image processing | Icons, diagrams, scalable graphics |
| Scaling | Can become blurry if not handled | Scales cleanly |
| Interactivity | Handled manually with coordinates | Can attach events to elements |
Use canvas when you need fast pixel-based drawing or frequent redraws. Use SVG when you need scalable shapes, accessible vector graphics, or individual elements that can be styled and interacted with.
Common Canvas Mistakes
- Forgetting to set width and height attributes.
- Stretching canvas with CSS and making drawings blurry.
- Expecting drawn shapes to behave like HTML elements.
- Putting important text only inside canvas without an accessible alternative.
- Redrawing inefficiently and hurting performance.
- Using canvas when SVG or normal HTML would be simpler.
Canvas in HTML is powerful for dynamic graphics, but it should be used for the right job. It gives you a blank drawing surface controlled by JavaScript. Use it for charts, games, drawing tools, simulations, and pixel-based graphics, while remembering that accessibility and responsiveness need deliberate planning.
Can canvas draw without JavaScript?
The canvas element creates the drawing area, but practical drawing on canvas is done with JavaScript.
Is canvas better than SVG?
Neither is always better. Canvas is better for pixel-heavy dynamic drawing, while SVG is better for scalable vector graphics and element-level interaction.
Continue learning HTML in order
Follow the topic sequence with the previous and next lesson.