Business requirements: Click on the picture hotspot to jump to different link addresses, while adapting to window size changes.
Problem: Hot zone coordinates do not change with window adjustment
Solution: Get the ratio of the initial coordinate point to the width and height of the picture, then multiply the ratio by the adjusted window width and height, and get the new coordinate point.
Calculate the new coordinates according to the initial coordinates:
function adjustPosition(position) { // Get wide height var pageWidth = document.body.clientWidth; var pageHeight = document.body.clientHeight; // Picture original size var imageWidth = 1423; var imageHeigth = 1077; var each = position.split(","); for (var i = 0; i < each.length; i++) { if(i%2==0){ // New y-axis coordinates each[i] = Math.round(parseInt(each[i]) * pageHeight / imageHeigth).toString(); }else{ // New x-axis coordinates each[i] = Math.round(parseInt(each[i]) * pageWidth / imageWidth).toString(); } } var newPosition = ""; for (var j = 0; j < each.length; j++) { newPosition += each[j]; if (j < each.length - 1) { newPosition += ","; } } return newPosition; }
Get the coordinate value of the coords attribute and replace it with the newly calculated coordinate points:
function adjust() { var map = document.getElementById("CribMap"); var area=map.getElementsByTagName('area'); for (var i = 0; i < area.length; i++) { var oldCoords = area[i].getAttribute("coords"); var newcoords = adjustPosition(oldCoords); area[i].setAttribute("coords", newcoords); } }
Run: adjust();
This article refers to a large number of similar codes on the Internet, but because they can not run effectively, so the code has been adjusted to help people in need.