HTML Canvas
31 March 2025 | Category: HTML
The HTML <canvas>
element is used to draw graphics, such as shapes, images, and animations, via JavaScript. It provides a powerful way to create visual content dynamically on a web page.
1. Introduction to <canvas>
The <canvas>
element is a rectangular area on the web page where you can draw using JavaScript. Unlike images, it allows dynamic, script-driven drawing.
Syntax:
<canvas id="myCanvas" width="500" height="300"></canvas>
2. Getting the Canvas Context
To draw on the canvas, you need to obtain its drawing context using JavaScript.
Example:
<canvas id="myCanvas" width="500" height="300"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
</script>
The getContext("2d")
method returns a 2D drawing context.
3. Drawing Shapes
Drawing a Rectangle
ctx.fillStyle = "blue"; // Set color
ctx.fillRect(50, 50, 150, 100); // x, y, width, height
Drawing a Circle
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();
Drawing a Line
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 200);
ctx.strokeStyle = "green";
ctx.lineWidth = 5;
ctx.stroke();
4. Adding Text to Canvas
ctx.font = "30px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas!", 50, 50);
fillText
draws filled text, while strokeText
draws outlined text.
5. Working with Images
To draw an image on canvas:
var img = new Image();
img.src = "image.jpg";
img.onload = function() {
ctx.drawImage(img, 50, 50, 200, 150);
};
6. Canvas Animation
You can create animations using requestAnimationFrame()
.
var x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "blue";
ctx.fillRect(x, 50, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();
This continuously moves the rectangle across the canvas.
7. Handling User Input
You can detect mouse clicks or movements:
canvas.addEventListener("mousedown", function(event) {
console.log("Mouse clicked at", event.clientX, event.clientY);
});
8. Advanced Techniques
- Transformations (
translate
,rotate
,scale
) - Gradients and Patterns
- Compositing and Transparency
9. Conclusion
The HTML <canvas>
element is a powerful tool for creating graphics, animations, and interactive applications using JavaScript.