The <canvas>
element in HTML is a powerful tool for drawing graphics via JavaScript. It provides a space where you can create dynamic, scriptable rendering of 2D shapes, images, and even animations. The <canvas>
element is a bitmap area, meaning you can draw and manipulate individual pixels directly on the screen.
The <canvas>
element itself doesn't display anything unless it is drawn on using JavaScript. It is defined with a width
and height
attribute, which sets the dimensions of the canvas area.
<canvas id="myCanvas" width="500" height="400"> Your browser does not support the canvas element. </canvas>
The text inside the <canvas>
element, like "Your browser does not support the canvas element," will be displayed if the browser doesn't support the canvas or JavaScript is disabled.
To draw on the canvas, you need to get a reference to the <canvas>
element in JavaScript and use the getContext()
method to obtain the 2D rendering context. Once you have the context, you can use various methods to draw shapes, text, or images.
Example of Drawing a Rectangle:
<script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "blue"; ctx.fillRect(50, 50, 200, 100); // Draw a filled rectangle </script>
In this example, the getContext("2d")
method retrieves the 2D drawing context. The fillStyle
property sets the fill color, and fillRect(x, y, width, height)
draws a blue rectangle at position (50, 50) with a width of 200 pixels and height of 100 pixels.
The canvas element provides various methods for drawing shapes, paths, and images. Some commonly used methods include:
beginPath()
: Starts a new path (needed to create new shapes).moveTo(x, y)
: Moves the drawing cursor to a specified point.lineTo(x, y)
: Draws a line from the current position to a new position.arc(x, y, radius, startAngle, endAngle, anticlockwise)
: Draws an arc or circle.stroke()
: Renders the outline of the shape.Example of Drawing a Line and Circle:
<script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); // Draw a line ctx.beginPath(); ctx.moveTo(50, 150); ctx.lineTo(200, 150); ctx.stroke(); // Draw the path // Draw a circle ctx.beginPath(); ctx.arc(100, 250, 50, 0, Math.PI * 2, false); // Circle at (100, 250) with radius 50 ctx.stroke(); // Draw the outline </script>
In this example, a line is drawn from (50, 150) to (200, 150), and a circle is drawn at (100, 250) with a radius of 50.
You can also draw images onto the canvas using the drawImage()
method. This method allows you to display images on the canvas and manipulate them (scale, rotate, etc.).
Example of Drawing an Image:
<script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.src = "image.jpg"; // Image source img.onload = function() { ctx.drawImage(img, 50, 50, 200, 150); // Draw image on canvas at (50, 50) with size 200x150 }; </script>
The img.onload
function ensures that the image is fully loaded before trying to draw it onto the canvas. The drawImage(image, x, y, width, height)
method then draws the image at the specified coordinates and with the specified dimensions.
You can also create animations by repeatedly clearing and redrawing on the canvas. To achieve this, you would typically use requestAnimationFrame()
to create smooth animations, reducing the CPU usage compared to traditional setInterval()
or setTimeout()
.
Example of Animating a Moving Ball:
<script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var x = 50; var y = 50; var dx = 2; var dy = 2; function drawBall() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas ctx.beginPath(); ctx.arc(x, y, 20, 0, Math.PI * 2, false); // Draw the ball ctx.fillStyle = "red"; ctx.fill(); ctx.stroke(); // Update the position of the ball x += dx; y += dy; // Bounce the ball off the edges if (x + dx > canvas.width || x + dx < 0) { dx = -dx; } if (y + dy > canvas.height || y + dy < 0) { dy = -dy; } requestAnimationFrame(drawBall); // Request next frame } drawBall(); // Start the animation </script>
In this example, a red ball moves around the canvas, bouncing off the edges. The clearRect()
method clears the canvas at each frame to create a smooth animation, and requestAnimationFrame(drawBall)
is used to continuously redraw the ball at its new position.
The <canvas>
element in HTML provides a powerful way to draw graphics directly on the web page using JavaScript. Whether you're creating simple shapes, complex images, or dynamic animations, the <canvas>
element allows you to do it all. By using various methods like fillRect()
, arc()
, drawImage()
, and more, you can create rich visual content in your web applications.