HTML canvas closePath() Method
Example
Draw a path, shaped as the letter L, and close the path with a line back to the starting point:
JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.closePath();
ctx.stroke();
Try it Yourself »
Description
The closePath()
method creates a path from the current point back to the starting point.
Use the stroke()
or fill()
method to draw the path.
Syntax
context.closePath() |
Parameters
NONE |
Return Value
NONE |
More Examples
Example
Fill the path with the color black:
JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.closePath();
ctx.stroke();
Try it Yourself »
Example
Fill the path with the color red:
JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
Try it Yourself »
Browser Support
The <canvas>
element is an HTML5 standard (2014).
closePath()
is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
❮ Canvas API