html tutorial - fill() Method in HTML5 Canvas - html5 - html code - html form

Learn html - html tutorial - Fill method in html5 canvas - html examples - html programs
- The fill() method is one of the canvas method.
- This method is used to fills the current drawing (path).
Syntax for fill() method in HTML5 CANVAS:
context . fill( ) ;
Sample coding for fill() method in HTML5 Canvas:
Tryit<!DOCTYPE html>
<html>
<head>
<title>wikitechy - HTML canvas fill() method </title>
</head>
<body>
<h1>wikitechy-HTML canvas fill() method with example: </h1>
<canvas id="wikitechyCanvas" width="500" height="250"
style="border:1px solid #d3d3d3;" ></canvas>
<script>
var m = document.getElementById("wikitechyCanvas") ;
var mas = m.getContext("2d") ;
mas.beginPath();
mas.rect(30, 30, 200, 150);
mas.fillStyle = "green" ;
mas.fill();
mas.beginPath();
mas.rect(60, 60, 200, 150);
mas.fillStyle = "red";
mas.fill();
</script>
</body>
</html>
Code Explanation for fill() method in HTML5 Canvas:

- “WikitechyCanvas” is used to declare the id value of the canvas tag.
- getElementById method is used to get the id value as “wikitechyCanvas” from the canvas for draw a rectangle on the canvas.
- getContext(“2d”) is used to draw a two-dimension figure on the canvas.
- beginpath() method is used to begins the path for rectangle.
- The fillStyle property is used to set the green color in first rectangle.
- The fill() method is used to fill green color to the first rectangle.
- fillStyle property is used to set the red color in second rectangle.
- The fill() method is used to fill the second rectangle.
Output for fill() method in HTML5 Canvas:

- The output shows that a canvas rectangle with width as 500 and height as 250.
- The first rectangle filled with green color.
- The second rectangle filled with red color.
Browser Support for fill() method in HTML5 Canvas:
![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|
Yes | 9.0 | Yes | Yes | Yes |
Tips and Notes
- The fillstyle property is used to fill the another color or gradient.
- If the path is not closed, the fill() method will add a line from the last point to the startpoint of the path to close the path, and then fill the path.