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

วิธีวาดวงกลมใน HTML5 SVG

SVG (Scalable Vector Graphics) เป็นกราฟิกเวกเตอร์ที่ขยายได้ไม่เสียคุณภาพ วาดวงกลมด้วยแท็ก <circle> ภายใน <svg>

Attribute ของ <circle>

Attributeคำอธิบาย
cxX coordinate ของจุดศูนย์กลาง
cyY coordinate ของจุดศูนย์กลาง
rรัศมี (radius)
fillสีเติม (CSS color)
strokeสีขอบ
stroke-widthความหนาขอบ

ตัวอย่างพื้นฐาน

<!DOCTYPE html>
<html>
<head>
  <title>HTML5 SVG Circle</title>
  <style>
    #svgelem { position: relative; left: 10%; transform: translateX(-20%); }
  </style>
</head>
<body>
  <h2>HTML5 SVG Circle</h2>
  <svg id="svgelem" height="200" xmlns="https://www.w3.org/2000/svg">
    <circle id="greencircle" cx="60" cy="60" r="50" fill="green" />
  </svg>
</body>
</html>

ตัวอย่างขั้นสูง

<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- วงกลมพื้นหลัง -->
  <circle cx="100" cy="100" r="90" fill="none" stroke="#ddd" stroke-width="10" />
  <!-- วงกลมความคืบหน้า -->
  <circle cx="100" cy="100" r="90" fill="none" stroke="#4CAF50" stroke-width="10"
    stroke-dasharray="565" stroke-dashoffset="113" 
    style="transform: rotate(-90deg); transform-origin: center;" />
  <text x="100" y="105" text-anchor="middle" font-size="24" fill="#333">80%</text>
</svg>

SVG vs Canvas

SVGCanvas
Vector (resolution independent)Raster (pixel-based)
DOM elements (accessible, styleable)Bitmap (single element)
เหมาะ: icons, charts, illustrationsเหมาะ: games, image processing, real-time
ช้าเมื่อ element เยอะมากเร็วสำหรับ animation จำนวนมาก

Browser Support

รองรับทุก browser รุ่นใหม่ รวม IE9+ (ต้องมี xmlns="https://www.w3.org/2000/svg")