บทนำ
มี 3 วิธีหลักในการวาดวงกลมใน HTML:
- SVG - ใช้
<circle>(แนะนำสำหรับกราฟิกเวกเตอร์) - Canvas - ใช้
arc()(แนะนำสำหรับแอนิเมชัน/เกม) - CSS - ใช้
border-radius: 50%(แนะนำสำหรับ UI/Layout)
วิธี CSS (ง่ายที่สุดสำหรับ UI)
<!DOCTYPE html>
<html>
<head>
<style>
#circle {
width: 50px;
height: 50px;
border-radius: 50%;
background: blue;
}
</style>
</head>
<body>
<div id="circle"></div>
</body>
</html>
วิธี SVG
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="blue" />
</svg>
วิธี Canvas
<canvas id="c" width="100" height="100"></canvas>
<script>
var ctx = document.getElementById('c').getContext('2d');
ctx.beginPath();
ctx.arc(50, 50, 40, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
</script>
เปรียบเทียบ
| วิธี | ข้อดี | เหมาะสำหรับ |
|---|---|---|
| CSS | ง่าย ใช้กับ Layout ได้ ไม่ต้อง JS | ปุ่ม, อะวาตาร์, Indicator |
| SVG | เวกเตอร์ DOM เข้าถึงได้ | ไอคอน, ชาร์ท, Illustration |
| Canvas | ประสิทธิภาพสูงสำหรับหลายวัตถุ | เกม, แอนิเมชันซับซ้อน |