การวาดวงกลมผ่าน canvas บน JavaScript
เมธอด arc ต่อไปนี้จะวาดส่วนโค้งที่มีจุดศูนย์กลางที่จุดใดจุดหนึ่ง โดยรับพารามิเตอร์ต่อไปนี้: x, y, รัศมี r, มุมเริ่มต้น startAngle, มุมสิ้นสุด endAngle, การวาดตามหรือทวนเข็มนาฬิกา direction
พารามิเตอร์ direction รับค่าต่อไปนี้: true ทำให้วาดตามเข็มนาฬิกา, false ทำให้วาดทวนเข็มนาฬิกา (ค่าเริ่มต้น)
ทั้งนี้ มุมในเมธอด arc จะวัดเป็น เรเดียน ไม่ใช่เป็นองศา หากต้องการแปลงองศาเป็นเรเดียน คุณสามารถใช้ฟังก์ชันต่อไปนี้:
function getRadians(degrees) {
return (Math.PI / 180) * degrees;
}
วาดวงกลม
<canvas width="200" height="200" style="background: #f4f4f4;"></canvas>
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
ctx.arc(100, 100, 75, 0, getRadians(360));
ctx.stroke();
:
วาดครึ่งวงกลม
<canvas width="200" height="200" style="background: #f4f4f4;"></canvas>
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
ctx.arc(100, 100, 75, 0, getRadians(180));
ctx.stroke();
:
วาดครึ่งวงกลมทึบ
<canvas width="200" height="200" style="background: #f4f4f4;"></canvas>
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
ctx.arc(100, 100, 75, 0, getRadians(180));
ctx.fill(); // ระบายพื้นที่
: