HTML <canvas> Tag
Last Updated :
29 Mar, 2024
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.Â
Syntax
<canvas id = "script"> Contents... </canvas>
Note:
- The <canvas> tag is new in HTML5.
- The following are the default values for <canvas> element that can be displayed by most of the Browsers:
canvas { Â
height:Â 150px;Â
width:Â 300px;
}
Attributes
The <canvas> tag accepts two attributes which are described below:
height
|
This attribute is used to set the height of the canvas by taking the value in pixels and its default value is 150.
|
width
|
This attribute is used to set the width of the canvas by taking the value in pixels and its default value is 300.
|
The <canvas> tag supports both Global Attributes & Event Attributes in HTML.
Example 1:Â In this example, we will create a canvas element with a width of 200 pixels and a height of 100 pixels, displayed with a black border.
HTML
<!DOCTYPE html>
< html >
< body >
< canvas id = "GeeksforGeeks"
width = "200" height = "100"
style = "border:1px solid black" >
</ canvas >
</ body >
</ html >
|
Output:Â
Â
Example 2:Â In this example, a 200×200 canvas with ID “geeks” displays a black-bordered circle at coordinates (100,100) using HTML5 Canvas.
HTML
<!DOCTYPE html>
< html >
< body >
< canvas id = "geeks"
height = "200"
width = "200"
style = "border:1px solid black" >
</ canvas >
< script >
var c = document.getElementById("geeks");
var cx = c.getContext("2d");
cx.beginPath();
cx.arc(100, 100, 90, 0, 2 * Math.PI);
cx.stroke();
</ script >
</ body >
</ html >
|
Output:Â
Example 3:Â In this example, a 200×200 canvas with ID “geeks” displays a radial gradient that transitions from red to green, filling the entire canvas using HTML5 Canvas.
HTML
<!DOCTYPE html>
< html >
< body >
< canvas id = "geeks"
width = "200"
height = "200"
style = "border:1px solid black" >
</ canvas >
< script >
var c = document.getElementById("geeks");
var cx = c.getContext("2d");
var 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 >
|
Output:Â
Supported Browsers
- Google Chrome 1.0 and above
- Edge 12.0 and above
- Firefox 1.5 and above
- Opera 9.0 and above
- Safari 2.0 and above
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...