About Lesson
HTML Canvas is a powerful feature that allows you to draw and manipulate graphics on a web page using JavaScript. Here’s an overview of HTML Canvas graphics:
- Creating a Canvas:
To use HTML Canvas, you need to create a<canvas>
element in your HTML markup. This element provides a drawing surface. Example:
<canvas id="myCanvas" width="500" height="300"></canvas>
- Obtaining the Canvas Context:
To draw on the canvas, you need to obtain the 2D rendering context using JavaScript. This context object provides methods and properties for drawing on the canvas. Example:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
- Drawing Shapes:
The canvas context provides methods to draw basic shapes like rectangles, circles, lines, and more. Here are a few examples:
- Drawing a Rectangle:
ctx.fillStyle = "red"; // Set the fill color
ctx.fillRect(50, 50, 100, 80); // Draw a filled rectangle
- Drawing a Circle:
ctx.fillStyle = "blue"; // Set the fill color
ctx.beginPath();
ctx.arc(200, 150, 50, 0, 2 * Math.PI); // Draw a circle path
ctx.fill(); // Fill the circle
- Drawing a Line:
ctx.strokeStyle = "green"; // Set the stroke color
ctx.lineWidth = 2; // Set the line width
ctx.beginPath();
ctx.moveTo(250, 50); // Move to the starting point
ctx.lineTo(400, 150); // Draw a line to the ending point
ctx.stroke(); // Stroke the line
- Applying Styles and Colors:
You can set various styles and colors to customize the appearance of your graphics. The canvas context provides methods and properties for controlling colors, gradients, transparency, line styles, and more. Example:
ctx.fillStyle = "red"; // Set the fill color
ctx.strokeStyle = "green"; // Set the stroke color
ctx.lineWidth = 2; // Set the line width
ctx.globalAlpha = 0.5; // Set the transparency
- Manipulating Pixels:
You can manipulate individual pixels on the canvas using the canvas context’sgetImageData()
andputImageData()
methods. This allows for pixel-level image processing and effects.
These are just a few examples of what you can do with HTML Canvas graphics. With the canvas context and its methods, you have the flexibility to create complex drawings, animations, interactive graphics, and more. JavaScript provides a wide range of tools and techniques to work with canvas graphics, allowing you to create dynamic and visually appealing web applications.
Join the conversation