ใช้แอตทริบิวต์ 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)
- เปิดรูปภาพใน Image Editor (Paint, Photoshop, GIMP, ออนไลน์)
- วางเมาส์ที่จุดที่ต้องการ - ดูพิกัด X, Y
- หรือใช้ 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