Welcome to our comprehensive guide on HTML Canvas! This tutorial is designed to help both beginners and intermediates understand the ins and outs of this powerful feature. š HTML Canvas is a built-in HTML5 tag used to draw graphics, animations, and interactive graphics within web browsers. Let's dive in!
To use the Canvas, you first need to include it in your HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Canvas Tutorial</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="400"></canvas>
<script src="canvas.js"></script>
</body>
</html>š Note: The canvas tag is empty and requires width and height attributes. The corresponding script (canvas.js in this case) contains the JavaScript code to draw on the canvas.
To draw on the canvas, you'll use JavaScript and the getContext() method to get a 2D drawing context. Here's a simple example:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#F8B195'; // Set the fill color
ctx.fillRect(10, 10, 150, 100); // Draw a rectangleš Note: The fillStyle property sets the drawing color, and the fillRect() method draws a filled rectangle.
The Canvas context offers a variety of methods for creating different shapes, images, and text. Here are some essential ones:
clearRect(x, y, width, height) - Clears a rectangular area.strokeRect(x, y, width, height) - Draws an outlined rectangle.arc(x, y, radius, startAngle, endAngle, anticlockwise) - Draws an arc.fillText(text, x, y [, maxWidth]) - Draws text inside a canvas.drawImage(image, x, y [, width [, height]]) - Draws an image.For more complex graphics, you can use paths, gradients, and patterns. Here's a simple example of drawing a gradient:
const gradient = ctx.createLinearGradient(0, 0, 0, 200);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 150, 100);š Note: The createLinearGradient() method creates a linear gradient, and the addColorStop() method adds a color at a specific position.
What method is used to clear a rectangular area on the canvas?
That's it for our HTML Canvas Reference! We hope this tutorial helps you create amazing graphics and animations with HTML Canvas. Stay tuned for more tutorials on CodeYourCraft! šÆ Happy coding!