249 of 264 menu

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

context.closePath();

Example

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

<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas> let 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:

<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas> let 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:

<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas> let 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
byenru