248 of 264 menu

beginPath method

The beginPath method must be called at the start of drawing a line using a combination of the moveTo and lineTo methods.

Syntax

context.beginPath();

Example

Let's draw a line:

<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.stroke();

:

Example

Let's draw a square:

<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(); ctx.stroke();

:

See also

  • the moveTo method
    that moves the pen to draw
  • the lineTo method
    that draws lines
byenru