Canvas closePath() Method

Definition and usage

closePath() Method to create a path from the current point to the starting point.

Tip:Please use stroke() Method to draw an exact path on the canvas.

Tip:Please use fill() Method to fill an image (default is black). Please use fillStyle Attribute to fill another color/gradient.

Instance

Example 1

Draw a path in the shape of the letter L, and then draw lines to return to the starting point:

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(20,100);
ctx.lineTo(70,100);
ctx.closePath();
ctx.stroke();

Try it yourself

Tip:More examples are provided at the bottom of the page.

Syntax

context.closePath();

More examples

Example 2

Set green as the fill color:

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(20,100);
ctx.lineTo(70,100);
ctx.closePath();
ctx.stroke();
ctx.fillStyle="green";
ctx.fill();

Try it yourself

Browser support

The numbers in the table indicate the first browser version to fully support this attribute.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.