The <canvas> tag in HTML is used to draw graphics on a web page using JavaScript. It can be used to draw paths, boxes, texts, gradients, and adding images. By default, it does not contain borders and text.
<!DOCTYPE html>
<html>
<body>
<canvas id="GeeksforGeeks"
width="200" height="100"
style="border:1px solid black">
</canvas>
</body>
</html>
Syntax
<canvas id = "script"> Contents... </canvas>Note: The <canvas> tag is new in HTML5.
Attributes
The <canvas> tag accepts two attributes which are described below:
Attributes | Descriptions |
|---|---|
This attribute is used to set the height of the canvas by taking the value in pixels and its default value is 150. | |
This attribute is used to set the width of the canvas by taking the value in pixels and its default value is 300. |
Use canvas tag with JavaScript
<!DOCTYPE html>
<html>
<body>
<canvas id="geeks"
height="200"
width="200"
style="border:1px solid black">
</canvas>
<script>
let c = document.getElementById("geeks");
let cx = c.getContext("2d");
cx.beginPath();
cx.arc(100, 100, 90, 0, 2 * Math.PI);
cx.stroke();
</script>
</body>
</html>
More Example
<!DOCTYPE html>
<html>
<body>
<canvas id="geeks"
width="200"
height="200"
style="border:1px solid black">
</canvas>
<script>
let c = document.getElementById("geeks");
let cx = c.getContext("2d");
let grd = cx.createRadialGradient
(100, 100, 5, 100, 100, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "green");
cx.fillStyle = grd;
cx.fillRect(0, 0, 200, 200);
</script>
</body>
</html>