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




Fill method in html5 canvas

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:

fill() method in HTML5 canvas Code Explanation

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

Output for fill() method in HTML5 Canvas:

fill() method in HTML5 canvas Output

  1. The output shows that a canvas rectangle with width as 500 and height as 250.
  2. The first rectangle filled with green color.
  3. 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.

Related Searches to fill() Method in HTML5 Canvas