เมธอด beginPath

เมธอด beginPath ควรถูกเรียก เมื่อเริ่มต้นวาดเส้นโดยใช้การผสมผสาน ของเมธอด moveTo และ lineTo

ไวยากรณ์

javascriptcontext.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,
    ซึ่งวาดเส้น