HTML Canvas Tutorial
The <canvas>
tag is used to draw graphics on a web page using JavaScript. This tag is like a drawing board where you can create shapes, lines, text, and even images.
How to Use <canvas>
First, you need to add the <canvas>
tag to your HTML:
<canvas id="myCanvas" width="200" height="100"></canvas>
Next, you can use JavaScript to draw on the canvas. You can access the canvas element using the getElementById()
method and then use the canvas drawing functions to create graphics.
Main Attributes of <canvas>
Attribute | Description |
---|---|
width | Sets the width of the canvas in pixels. |
height | Sets the height of the canvas in pixels. |
id | Sets an ID for the canvas element, which can be used to select the canvas using JavaScript. |
style | Allows you to apply CSS styles to the canvas element to control its appearance. |
Example
Here is an example code snippet showing how to create a simple rectangle on a canvas:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 50, 50);
In the code above, we first get the canvas element by its ID, then we get the 2D drawing context of the canvas using the getContext()
method. We set the fill color to blue and draw a rectangle at position (10, 10) with a width and height of 50 pixels each.