closePath method

The closePath method automatically closes a shape drawn with the lineTo method, drawing a straight line from the end point to initial. If the shape has already been closed or is just a point, then the method does nothing.

Syntax

javascriptcontext.closePath();

Example

First, we draw two lines without closing them with closePath:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptlet canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(100, 100);
ctx.lineTo(150, 50);
ctx.stroke();

Результат:

Example

And now let's close these two lines into a shape through closePath, thereby obtaining a triangle:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptlet canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(100, 100);
ctx.lineTo(150, 50);
ctx.closePath(); // closes the lines into a shape
ctx.stroke();

Результат:

Example

Let's draw a square, instead of the last line, closing the shape via closePath:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptlet canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(150, 150);
ctx.lineTo(50, 150);
ctx.closePath(); // closes the lines into a shape
ctx.stroke();

Результат:

See also

  • the fill method
    that paints a shape with a given color