HTML5 Canvas Reference - closePath()








The closePath() method creates a path by connecting the current point and the starting point.

After closing the path we can call stroke() method to draw the path.

We can also call the fill() method to fill the path with black color as the default.

To change the color we can use the fillStyle property to fill with another color or gradient or pattern.

Browser compatibility

closePath() Yes Yes Yes Yes Yes

JavaScript syntax

context.closePath();




Example

The following code draws a path by connecting several lines. After adding lines it calls the closePath() to connect the ending point to the starting point.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from w ww .  j av a 2  s. co  m-->
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 80);
ctx.lineTo(70, 50);
ctx.lineTo(170, 150);
ctx.closePath();
ctx.stroke();

</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code uses the same coordinate value but calls the fill() method to fill the path with black color.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--  w  ww  . j a  v a  2 s. c  o  m-->
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 80);
ctx.lineTo(70, 50);
ctx.lineTo(170, 150);
ctx.closePath();
ctx.fill();

</script>

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to draw a car.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500px' height='200px'/>
<script type='text/javascript'>
    var canvas= document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
<!--   w w w.j a v  a2 s  .  co m-->
    var renderedCtx = canvas.getContext('2d');
    renderedCtx.fillStyle = 'red';
    renderedCtx.fillRect(5, 30, 90, 30); // Lateral
    renderedCtx.fillRect(30, 5, 40, 30); // Lateral
    renderedCtx.fillStyle = '#000';
    // Roda 1
    renderedCtx.beginPath();
    renderedCtx.arc(30, 60, 10, 0, Math.PI*2, true); 
    renderedCtx.closePath();
    renderedCtx.fill();
    // Roda 2
    renderedCtx.beginPath();
    renderedCtx.arc(75, 60, 10, 0, Math.PI*2, true); 
    renderedCtx.closePath();
    renderedCtx.fill();
    var canvas = document.getElementById('mycanvas');
    var ctx = canvas.getContext('2d');
    ctx.drawImage(rendered, 10 ,10);
</script>
</body>
</html>

The code above is rendered as follows: