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

javascriptcontext.beginPath();

Example

Let's draw a line:

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

Результат:

Example

Let's draw a square:

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

Результат:

See also

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