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