The HTML <canvas>
element is used to draw graphics via JavaScript. It provides an area on a web page where you can render dynamic graphics such as images, shapes, animations, and other visual elements. It acts as a blank space that can be manipulated via the JavaScript API, providing a powerful tool for games, data visualization, and interactive graphics.
Basic Syntax
<canvas id="myCanvas" width="500" height="500"></canvas>
id
: An identifier for the canvas, used to access it in JavaScript.width
andheight
: Define the size of the canvas. If not specified, the default size is 300px by 150px.
Accessing the Canvas in JavaScript
To draw on the canvas, you must first get a reference to the canvas element and its 2D rendering context.
// Get the canvas element
var canvas = document.getElementById('myCanvas');
// Get the 2D drawing context
var ctx = canvas.getContext('2d');
Drawing on the Canvas
Once you have the context, you can start drawing. Here are a few examples of basic shapes and operations.
Drawing a Rectangle
ctx.fillStyle = "#FF0000"; // Set the color to red
ctx.fillRect(50, 50, 150, 100); // Draw a filled rectangle (x, y, width, height)
Drawing a Circle
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2); // Draw a circle (x, y, radius, startAngle, endAngle)
ctx.fillStyle = "blue";
ctx.fill(); // Fill the circle with color
Drawing a Line
ctx.beginPath();
ctx.moveTo(10, 10); // Starting point
ctx.lineTo(200, 200); // Ending point
ctx.stroke(); // Actually draw the line
Drawing Text
ctx.font = "30px Arial"; // Set font size and type
ctx.fillStyle = "green"; // Set text color
ctx.fillText("Hello, Canvas!", 50, 150); // Draw the text at position (50, 150)
Clearing the Canvas
To clear or reset the canvas, you can use the clearRect()
method:
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clears the entire canvas
Animating on the Canvas
You can create animations by using the requestAnimationFrame
method, which allows you to draw continuously on the canvas in an efficient way.
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas on each frame
ctx.beginPath();
ctx.arc(x, 100, 30, 0, Math.PI * 2); // Draw a circle that moves horizontally
ctx.fillStyle = "purple";
ctx.fill();
x += 2; // Move the circle to the right
requestAnimationFrame(animate); // Request the next frame
}
animate(); // Start the animation
Example of Drawing a Basic Shape (Full Example)
Here's a complete example of using the canvas to draw a red rectangle and a blue circle:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Example</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Draw a red rectangle
ctx.fillStyle = '#FF0000';
ctx.fillRect(50, 50, 200, 150);
// Draw a blue circle
ctx.beginPath();
ctx.arc(300, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
</script>
</body>
</html>
Advanced Usage
- Paths and Curves: The canvas can also be used to draw complex paths and curves using methods like
moveTo()
,lineTo()
,arcTo()
, andbezierCurveTo()
. - Images: You can load and draw images onto the canvas using
drawImage()
. - Gradients and Patterns: You can use gradients (linear or radial) or even create patterns from images for fills.
Example: Using an Image
var img = new Image();
img.src = 'path/to/image.jpg';
img.onload = function() {
ctx.drawImage(img, 0, 0, 200, 200); // Draw the image at (0,0) with width and height 200x200
}
Conclusion
The <canvas>
element offers a robust and versatile method for creating interactive and dynamic graphics on the web. By using JavaScript in combination with the 2D context API, you can draw shapes, images, text, and animations, making it a great tool for creating games, visualizations, and custom animations.
No comments:
Post a Comment