The <canvas>
tag in HTML is used to draw graphics on a web page via JavaScript. It provides an area where 2D shapes, images, text, and even 3D content can be rendered using JavaScript's CanvasRenderingContext2D
or WebGL
API.
Here’s a comprehensive explanation with examples:
1. Basic Structure of the <canvas>
Element
The <canvas> tag itself does not draw anything. It provides a placeholder that can be dynamically manipulated using JavaScript. It has width and height attributes, which define the size of the canvas.
Example:
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"> </canvas>
In this example:
- The
id="myCanvas"
is used to target the canvas element with JavaScript. width="400"
andheight="400"
define the size of the canvas.- The inline
style
adds a border to visually see the canvas on the page.
2. JavaScript for Drawing on the Canvas
To draw on the canvas, we use JavaScript. The canvas rendering context is an object containing the drawing methods and properties.
Example:
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"> </canvas> <script> // Get the canvas element and its drawing context var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); // Drawing a filled rectangle ctx.fillStyle = "blue"; // Set fill color ctx.fillRect(50, 50, 150, 100); // Draw a rectangle (x, y, width, height) </script>
getContext("2d")
: Returns a 2D drawing context.fillStyle
: Defines the fill color.fillRect(x, y, width, height)
: Draws a filled rectangle on the canvas.
3. Drawing Shapes
The canvas provides a wide range of methods to draw basic shapes like rectangles, circles, and paths.
Drawing a Rectangle:
ctx.fillStyle = "red"; ctx.fillRect(20, 20, 150, 100); // x, y, width, height
Drawing a Line:
ctx.beginPath(); // Start a new path ctx.moveTo(0, 0); // Move the pen to (0, 0) ctx.lineTo(200, 100); // Draw a line to (200, 100) ctx.stroke(); // Render the line
Drawing a Circle (Arc):
ctx.beginPath(); ctx.arc(100, 75, 50, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle ctx.stroke(); // Draw the circle outline
4. Adding Text to the Canvas
The canvas can also render text.
Example:
ctx.font = "30px Arial"; // Set the font size and family ctx.fillStyle = "green"; // Set text color ctx.fillText("Hello Canvas!", 50, 50); // (text, x, y)
font
: Sets the font size and style.fillText(text, x, y)
: Draws filled text.strokeText(text, x, y)
: Draws text with an outline (no fill).
5. Drawing Images on Canvas
Images can be drawn using the drawImage()
method.
Example:
var img = new Image(); img.src = 'path-to-your-image.jpg'; img.onload = function() { ctx.drawImage(img, 0, 0, 300, 200); // Draw the image once it's loaded };
drawImage(image, x, y, width, height)
: Draws the image at the specified coordinates with the given dimensions.
6. Canvas Transformations
The canvas allows transformations like translation, rotation, and scaling.
Translation:
Moves the origin of the canvas.
ctx.translate(100, 100); // Move the origin to (100, 100) ctx.fillRect(0, 0, 50, 50); // Draw a rectangle with new origin
Rotation:
Rotates the canvas around its current origin.
ctx.rotate((Math.PI / 180) * 45); // Rotate 45 degrees ctx.fillRect(50, 50, 100, 50); // Draw a rotated rectangle
Scaling:
Scales the canvas content.
ctx.scale(2, 2); // Scale horizontally and vertically by a factor of 2 ctx.fillRect(10, 10, 50, 50); // Draw a scaled rectangle
7. Canvas State Management
Before performing transformations, it’s common to save and restore the canvas state.
ctx.save()
: Saves the current state (transformations, styles, etc.).ctx.restore()
: Restores the canvas to the last saved state.
Example:
ctx.save(); // Save the current state ctx.rotate(0.5); // Rotate canvas ctx.fillRect(50, 50, 100, 100); // Draw a rectangle ctx.restore(); // Restore the canvas to the previous state
8. Drawing Gradients
Gradients allow you to create color transitions. The canvas supports both linear and radial gradients.
Linear Gradient Example:
var gradient = ctx.createLinearGradient(0, 0, 200, 0); gradient.addColorStop(0, "red"); gradient.addColorStop(1, "blue"); ctx.fillStyle = gradient; ctx.fillRect(10, 10, 200, 100); // Draw a rectangle filled with the gradient
Radial Gradient Example:
var radialGradient = ctx.createRadialGradient(75, 50, 5, 90, 60, 100); radialGradient.addColorStop(0, "yellow"); radialGradient.addColorStop(1, "green"); ctx.fillStyle = radialGradient; ctx.fillRect(10, 10, 200, 100); // Draw with radial gradient
9. Clipping
Clipping defines a specific area in the canvas where the rendering is restricted.
Example:
ctx.beginPath(); ctx.arc(100, 100, 75, 0, Math.PI * 2); ctx.clip(); // Clip the canvas to the circular path ctx.fillStyle = "blue"; ctx.fillRect(50, 50, 200, 200); // Only the part inside the circle will be drawn
10. Clearing the Canvas
You can clear a specific area or the entire canvas using the clearRect()
method.
Example:
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clears the entire canvas
11. Handling User Input (Mouse, Keyboard)
You can use JavaScript events to interact with the canvas based on user input.
Example: Drawing on Canvas with Mouse
<canvas id="drawCanvas" width="400" height="400" style="border:1px solid black;"> </canvas> <script> var canvas = document.getElementById("drawCanvas"); var ctx = canvas.getContext("2d"); var drawing = false; canvas.addEventListener("mousedown", function() { drawing = true; }); canvas.addEventListener("mouseup", function() { drawing = false; }); canvas.addEventListener("mousemove", draw); function draw(event) { if (!drawing) return; var x = event.clientX - canvas.offsetLeft; var y = event.clientY - canvas.offsetTop; ctx.fillRect(x, y, 2, 2); // Draw a small square } </script>
Conclusion
The <canvas>
tag provides a powerful and flexible tool for rendering 2D and 3D graphics in web applications. It works hand in hand with JavaScript to enable dynamic and interactive graphics, from simple shapes and images to complex animations and games.
By mastering basic shapes, transformations, gradients, and event handling, you can create engaging visuals for web projects.