HTML5 Canvas Reference - fill()








The fill() method fills the current path with the default color black.

To change the fill color set the fillStyle property for another color/gradient.

If the path is not closed, the fill() method will connect the last point and the startpoint to close the path, and then fill the path.

Browser compatibility

fill() Yes Yes Yes Yes Yes

JavaScript syntax

context.fill();




Example

The following code draws a rectangle and fill it with the color red:


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from ww w  .  j  av  a2  s  .  com-->
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.rect(50, 50, 150, 100);
    ctx.fillStyle = "red";
    ctx.fill();

</script> 
</body>
</html>

The code above is rendered as follows:





Example 2

The following code creates two shapes and fill them with different colors.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from ww  w  .ja  va2 s . c o  m-->
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(100, 100);
    ctx.arc(100, 100, 100, 90 * Math.PI / 180, 450 * Math.PI / 180);
    ctx.fill();
    ctx.beginPath();
    ctx.moveTo(310, 100);
    
    ctx.arc(310, 100, 100, 0 * Math.PI / 180, 360 * Math.PI / 180);
    ctx.fillStyle = "red";
    ctx.fill();



</script>
</body>
</html>

The code above is rendered as follows: