HTML Canvas
HTML5 Canvas API
Section titled “HTML5 Canvas API”The HTML <canvas> element provides a powerful way to draw graphics, animations, and manipulate images dynamically on a web page using JavaScript.
Example Canvas Output:
Section titled “Example Canvas Output:”<!-- The canvas element itself is just a container --><canvas id="myDemoCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML canvas tag. <!-- Fallback content --></canvas>
<p>The graphics inside the border above were drawn using the Canvas API.</p>(JavaScript code is required to draw on the canvas, see examples below).
What is HTML Canvas?
Section titled “What is HTML Canvas?”The <canvas> element creates a fixed-size drawing surface on the page.
It acts as a container; you use JavaScript to access its rendering context (usually the 2D context) and call methods on that context to draw shapes, text, images, etc.
Think of it like a digital canvas you can paint on with code.
Browser Support
Section titled “Browser Support”The <canvas> element and its 2D rendering context are widely supported by all modern web browsers.
Basic Canvas Usage
Section titled “Basic Canvas Usage”1. Add the <canvas> Element to HTML
Section titled “1. Add the <canvas> Element to HTML”Include the <canvas> tag in your HTML, giving it an id (to reference it in JavaScript) and specifying its width and height attributes.
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000;"> Fallback content for older browsers.</canvas>Note: It’s important to set width and height using the HTML attributes, not just CSS. CSS sizing scales the canvas, while attributes define the actual drawing resolution.
2. Get the Rendering Context in JavaScript
Section titled “2. Get the Rendering Context in JavaScript”Use JavaScript to get a reference to the canvas element and then get its 2D rendering context.
const canvas = document.getElementById('myCanvas');// Check if canvas is supported before getting contextif (canvas.getContext) { const ctx = canvas.getContext('2d'); // You can now draw on the 'ctx' (context) object} else { // Canvas not supported console.error('Canvas API not supported in this browser.');}3. Draw on the Context
Section titled “3. Draw on the Context”Call methods on the ctx object to draw. Here are some common examples:
Drawing a Rectangle:
Section titled “Drawing a Rectangle:”// Set fill colorctx.fillStyle = 'red';// Draw a filled rectangle: fillRect(x, y, width, height)ctx.fillRect(10, 10, 150, 75);Drawing a Line:
Section titled “Drawing a Line:”// Set stroke colorctx.strokeStyle = 'blue';ctx.lineWidth = 3;
// Define path start pointctx.moveTo(0, 0);// Define path end pointctx.lineTo(200, 100);// Render the path (draw the line)ctx.stroke();Drawing a Circle:
Section titled “Drawing a Circle:”ctx.strokeStyle = 'green';ctx.lineWidth = 2;
// Begin a new pathctx.beginPath();// Draw an arc/circle: arc(x, y, radius, startAngle, endAngle)// Angles are in radians (0 to 2 * Math.PI for a full circle)ctx.arc(95, 50, 40, 0, 2 * Math.PI);// Render the path outlinectx.stroke();Drawing Text:
Section titled “Drawing Text:”// Set font stylectx.font = '24px Arial';ctx.fillStyle = 'purple';// Draw filled text: fillText(text, x, y)ctx.fillText('Hello Canvas!', 10, 50);
// Draw outlined text: strokeText(text, x, y)ctx.strokeStyle = 'black';ctx.strokeText('Outline', 10, 90);Drawing Gradients:
Section titled “Drawing Gradients:”// Create linear gradient: createLinearGradient(x0, y0, x1, y1)const gradient = ctx.createLinearGradient(0, 0, 200, 0);gradient.addColorStop(0, 'blue'); // Start colorgradient.addColorStop(1, 'white'); // End color
// Fill rectangle with gradientctx.fillStyle = gradient;ctx.fillRect(10, 10, 180, 80);Drawing Images:
Section titled “Drawing Images:”const img = new Image(); // Create new Image elementimg.onload = function() { // Draw image onto canvas: drawImage(image, x, y) ctx.drawImage(img, 10, 10); // Can also specify width/height: drawImage(image, x, y, width, height)};img.src = 'myImage.png'; // Set source path, triggers loadingAccessibility Considerations
Section titled “Accessibility Considerations”Content drawn on a <canvas> is not part of the DOM and is generally inaccessible to screen readers. If the canvas displays important information:
- Provide fallback content inside the
<canvas>tags. - Use ARIA attributes on the canvas element or related elements to describe its purpose or content.
- Provide the same information in an alternative, accessible format elsewhere on the page (e.g., a data table for a chart).
Common Use Cases
Section titled “Common Use Cases”Canvas is used for:
- Data visualization (charts, graphs)
- Simple games and animations
- Image manipulation and effects
- Online drawing or photo editing tools