HTML Canvas (Live Playground)
In this tutorial, we will learn how to use the HTML Canvas element to draw graphics, create animations, and build interactive applications on the web.
What is the HTML Canvas?
The HTML Canvas element is a feature of HTML5 that allows you to create and manipulate graphical content directly in your web browser. You can use the Canvas API (Application Programming Interface) to draw shapes, text, images, and even create animations.
Creating a Canvas Element
To create a canvas element, add the <canvas>
tag to your HTML document and set the width
and height
attributes:
<!DOCTYPE html>
<html>
<head>
<title>HTML Canvas Example</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="200"></canvas>
</body>
</html>
In this example, we created a canvas element with a width of 300 pixels and a height of 200 pixels. We also assigned an ID of myCanvas
to the element so that we can reference it in our JavaScript code.
Drawing on the Canvas
To draw on the canvas, you need to use JavaScript to access the Canvas API. First, get a reference to the canvas element using the getElementById()
method, and then call the getContext()
method to get a 2D drawing context:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
Now you can use the drawing context (ctx
) to draw shapes, text, and images on the canvas.
Drawing a Rectangle
To draw a rectangle, use the fillRect()
method:
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 75);
This example sets the fill color to blue and draws a filled rectangle with a width of 100 pixels and a height of 75 pixels at the position (50, 50) on the canvas.
Drawing Text
To draw text, use the fillText()
method:
ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello, Canvas!', 50, 150);
This example sets the font to "24px Arial" and the fill color to black, and then draws the text "Hello, Canvas!" at the position (50, 150) on the canvas.
Creating an Animation
To create an animation, you can use the requestAnimationFrame()
method to repeatedly update the canvas content:
let posX = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.fillStyle = 'red';
ctx.fillRect(posX, 50, 50, 50); // Draw a red square
posX += 2; // Update the x position
if (posX > 300) posX = 0;
requestAnimationFrame(draw); // Request the next frame
}
draw(); // Start the animation
In this example, we created a simple animation that moves a red square across the canvas. The draw()
function updates the canvas content, and the requestAnimationFrame()
method schedules the next frame update.
Conclusion
The HTML Canvas element is a powerful tool for creating graphics, animations, and interactive applications on the web. By using the Canvas API, you can draw shapes, text, and images, and even create complex animations directly in your web browser.