The CanvasRenderingContext2D.closePath() method of the Canvas 2D API attempts to add a straight line from the current point to the start of the current sub-path. If the shape has already been closed or has only one point, this function does nothing.

This method doesn't draw anything to the canvas directly. You can render the path using the CanvasRenderingContext2D.stroke() or CanvasRenderingContext2D.fill() methods.


void ctx.closePath();


Closing a triangle

This example creates the first two (diagonal) sides of a triangle using the lineTo() method. After that, the triangle's base is created with the closePath() method, which automatically connects the shape's first and last points.


<canvas id="canvas"></canvas>


var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.moveTo(20, 150);  // Move pen to bottom-left corner
ctx.lineTo(120, 20);  // Line to top corner
ctx.lineTo(220, 150); // Line to bottom-right corner
ctx.closePath();      // Line to bottom-left corner

Edit the code below to see your changes update live in the canvas:


Specification Status Comment
HTML Living Standard
The definition of 'CanvasRenderingContext2D.closePath' in that specification.
Living Standard  

Browser compatibility

Update compatibility data on GitHub
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung Internet
Basic supportChrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes


Full support  
Full support

See also

Document Tags and Contributors

Contributors to this page: mfluehr, fscholz, nmve, erikadoyle, Cath_kb
Last updated by: mfluehr,