HTML Canvas Basics
In the below PDF we discuss about HTML Canvas in detail in simple language, Hope this will help in better understanding.
How to Use HTML Canvas:
Setting Up the Canvas:
Before you can start drawing on a canvas, you need to set it up. You can create a canvas element in your HTML document like this:
<canvas id="myCanvas" width="500" height="300"></canvas>
The width and height attributes define the dimensions of your canvas. These dimensions will determine the drawing area, so choose them carefully based on your project’s requirements.
Drawing with the Context:
To draw on the canvas, you’ll need to access the rendering context. The most commonly used context is 2D. You can obtain the 2D context like this:
const canvas = document.getElementById("myCanvas");
const context = canvas.getContext("2d");
With the context in hand, you can start drawing shapes, lines, and more.
Basic Drawing Operations:
1. Drawing Rectangles:
To draw a rectangle, you can use the fillRect and strokeRect methods. fillRect fills the rectangle with a color, while strokeRect outlines it.
context.fillStyle = "blue";
context.fillRect(50, 50, 100, 100);
context.strokeStyle = "red";
context.strokeRect(200, 50, 100, 100);
2. Drawing Paths:
Paths are a series of connected lines and curves. You can use methods like beginPath, moveTo, lineTo, and arc to create intricate shapes and curves.
context.fillStyle = "green";
You can add text to your canvas using the fillText and strokeText methods.
context.font = "30px Arial";
context.fillStyle = "black";
context.fillText("Hello, Canvas!", 50, 150);
You can create an HTML canvas element using the <canvas> tag in your HTML code.
The context is an object that provides methods and properties for drawing on the canvas. You can obtain a 2D rendering context using the getContext() method,