JavaScript Canvas
The <canvas>
element in HTML5 is a container for graphics. By using the Canvas API
, you can draw 2D shapes, render images, create animations, and build interactive graphics directly within a webpage.
Key Topics
Drawing Shapes
Shapes like rectangles, circles, and lines can be drawn on the canvas using CanvasRenderingContext2D
methods.
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Draw a rectangle
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 150, 100);
// Draw a line
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 150);
ctx.strokeStyle = "red";
ctx.stroke();
Explanation: The fillRect
method draws a filled rectangle, and the moveTo
and lineTo
methods define and draw a line.
Canvas Text
Text can be rendered on the canvas using the fillText
or strokeText
methods. The text font and alignment can also be customized.
ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas", 100, 50);
ctx.strokeStyle = "blue";
ctx.strokeText("Outlined Text", 100, 100);
Explanation: The fillText
method draws filled text, while strokeText
draws text outlines. Font styles can be customized using the font
property.
Rendering Images
Images can be drawn on the canvas using the drawImage
method. This method also supports cropping and scaling.
const img = new Image();
img.src = "example.jpg";
img.onload = function() {
ctx.drawImage(img, 50, 50, 200, 100);
};
Explanation: The drawImage
method renders an image onto the canvas. The onload
event ensures the image is loaded before drawing.
Example: Canvas Graphics
Below is a comprehensive example demonstrating the use of the Canvas API to draw shapes, text, and images.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Canvas Example</title>
</head>
<body>
<canvas id="exampleCanvas" width="500" height="300" style="border:1px solid black;"></canvas>
<script>
const canvas = document.getElementById("exampleCanvas");
const ctx = canvas.getContext("2d");
// Draw rectangle
ctx.fillStyle = "lightblue";
ctx.fillRect(20, 20, 200, 100);
// Draw circle
ctx.beginPath();
ctx.arc(150, 200, 50, 0, 2 * Math.PI);
ctx.fillStyle = "green";
ctx.fill();
// Draw text
ctx.font = "18px Arial";
ctx.fillStyle = "black";
ctx.fillText("Canvas Graphics", 10, 290);
// Draw image
const img = new Image();
img.src = "example.jpg";
img.onload = function() {
ctx.drawImage(img, 250, 20, 200, 150);
};
</script>
</body>
</html>
Key Takeaways
- Canvas API: A powerful tool for creating 2D graphics and animations.
- Shapes: Use
fillRect
,arc
, and other methods to draw shapes. - Text Rendering: Render text with
fillText
andstrokeText
. - Image Manipulation: Use
drawImage
to render and manipulate images on the canvas.