HTML '<canvas>' Element
πΌοΈ Introduction to HTML Canvas
The HTML <canvas> element is a powerful feature that allows developers to draw graphics directly in the browser using JavaScript. It can be used to render shapes, images, animations, games, and data visualizations. Think of it as a blank drawing board within your webpage. π§
>>βCanvas turns code into visual creativity.β β A Developer's Paintbrush ποΈ
π Syntax of the <canvas> Element
Basic Canvas Syntax
<canvas id="myCanvas" width="300" height="150">
Your browser does not support the HTML canvas tag.
</canvas>Note
π‘ Always provide fallback content inside the <canvas> tag for older browsers.
βοΈ Accessing the Canvas with JavaScript
To draw on the canvas, you need to get its rendering context using JavaScript. The most common context is "2d", used for 2D graphics.
Get 2D Context
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");βοΈ Drawing Basics
π₯ Drawing a Rectangle
Draw Filled and Stroked Rectangles
// Filled rectangle
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);
// Stroked rectangle
ctx.strokeStyle = "blue";
ctx.strokeRect(10, 70, 100, 50);π Drawing a Circle (Arc)
Draw a Circle
ctx.beginPath();
ctx.arc(75, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "green";
ctx.fill();βοΈ Drawing Text
Draw Text on Canvas
ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas!", 10, 130);πΎ Embedding an Image
You can draw images onto the canvas using the drawImage() method.
Draw an Image
const img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
img.src = "image.jpg";Note
β οΈ The image must be fully loaded before drawing or it won't render properly.
π Animation with requestAnimationFrame
To create animations, you can use requestAnimationFrame() to repeatedly update the canvas.
Simple Animation
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 30, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();π§° Canvas Use Cases
- πΉοΈ Game Development (e.g., Pong, Snake, Flappy Bird)
- π Data Visualizations (e.g., bar charts, line graphs)
- ποΈ Drawing Tools (e.g., paint apps)
- π Image Editing & Effects
- π§ͺ Simulations and interactive art
π Useful Resources
>>βCode your imagination. Draw the impossible with <canvas>.β π¨