beginPathメソッド

メソッド beginPath は、 moveTo と lineTo メソッドの組み合わせを使用して 線を描画する際に最初に呼び出す必要があります。

構文

javascriptコンテキスト.beginPath();

例

線を描画してみましょう:

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

Результат:

例

四角形を描画してみましょう:

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

Результат:

関連項目

  • 描画ペンを移動するメソッド moveTo
  • 線を描画するメソッド lineTo