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

การตั้งค่ารูปร่างพื้นที่ (Shape) ใน HTML Image Map

ใช้แอตทริบิวต์ shape เพื่อตั้งค่ารูปร่างของพื้นที่ (Area) ใน HTML Image Map ใช้ร่วมกับ <map> และ <area>

ตัวอย่าง

ลองรันโค้ดต่อไปนี้เพื่อใช้งานแอตทริบิวต์ shape:

<!DOCTYPE html>
<html>
  <head>
    <title>HTML shape attribute</title>
  </head>
  <body>
    <img src="/images/html.gif" alt="HTML Map" border="0" usemap="#html">
    <!-- Create Mappings -->
    <map name="html">
      <area shape="circle" coords="154,150,59" href="about/about_team.htm" 
            alt="Team" target="_self" />
      <area shape="rect" coords="10,10,100,100" href="about/company.htm" alt="Company">
      <area shape="poly" coords="200,50, 250,100, 150,100" href="about/contact.htm" alt="Contact">
    </map>
  </body>
</html>

ค่า shape และ coords

Shape Coords Format คำอธิบาย
rect / rectangle x1,y1,x2,y2 สี่เหลี่ยม: มุมซ้ายบน (x1,y1) ถึง มุมขวาล่าง (x2,y2)
circle / circ x,y,r วงกลม: จุดศูนย์กลาง (x,y) และรัศมี r
poly / polygon x1,y1,x2,y2,...,xn,yn หลายเหลี่ยม: ลำดับจุดมุม (ต้องปิดเอง)
default (ไม่มี coords) พื้นที่ที่เหลือทั้งหมด (Fallback)

ตัวอย่างสมบูรณ์: Interactive Image Map

<img src="office-map.jpg" alt="Office Layout" usemap="#officeMap" style="max-width:100%">

<map name="officeMap">
  <!-- สี่เหลี่ยม: ห้องประชุม -->
  <area shape="rect" coords="50,50,250,150" 
        href="/meeting-room" alt="Meeting Room" title="Meeting Room - Click to book">
  
  <!-- วงกลม: โต๊ะกลม -->
  <area shape="circle" coords="400,100,40" 
        href="/round-table" alt="Round Table" title="Round Table">
  
  <!-- หลายเหลี่ยม: ห้องพักผ่อนรูปทรงแปลก -->
  <area shape="poly" coords="500,50, 600,20, 650,80, 620,150, 520,140" 
        href="/lounge" alt="Lounge" title="Relax Zone">
  
  <!-- Default: พื้นที่อื่นๆ -->
  <area shape="default" href="/floor-plan" alt="Full Floor Plan">
</map>

การได้พิกัด (Getting Coordinates)

  1. เปิดรูปภาพใน Image Editor (Paint, Photoshop, GIMP, ออนไลน์)
  2. วางเมาส์ที่จุดที่ต้องการ - ดูพิกัด X, Y
  3. หรือใช้ Online Image Map Generators: image-map.net, CSS Portal

JavaScript: จัดการ Click บน Area

<img src="map.jpg" usemap="#map" id="mapImg">
<map name="map">
  <area shape="rect" coords="10,10,100,100" data-action="open" data-id="1">
  <area shape="circle" coords="200,200,50" data-action="info" data-id="2">
</map>

<script>
document.querySelectorAll('area').forEach(area => {
  area.addEventListener('click', (e) => {
    e.preventDefault(); // ป้องกัน navigation
    const action = area.dataset.action;
    const id = area.dataset.id;
    console.log('Action:', action, 'ID:', id);
    // AJAX, Modal, etc.
  });
});
</script>

Accessibility

  • ใส่ alt ในทุก <area> (จำเป็น)
  • ใส่ title สำหรับ Tooltip
  • Tab Order: Area จะอยู่ใน Tab Order ตามลำดับใน Map

หมายเหตุ: Image Map ใช้งานยากบน Mobile (Touch) ควรพิจารณา UI ทางเลือก เช่น SVG Overlay หรือ Absolute Positioned Links