Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

วิธีวาดวงกลมในหน้า HTML


บทนำ

มี 3 วิธีหลักในการวาดวงกลมใน HTML:

  1. SVG - ใช้ <circle> (แนะนำสำหรับกราฟิกเวกเตอร์)
  2. Canvas - ใช้ arc() (แนะนำสำหรับแอนิเมชัน/เกม)
  3. 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ประสิทธิภาพสูงสำหรับหลายวัตถุเกม, แอนิเมชันซับซ้อน