Advertisement
jcunews

HighlightMapAreas.js

Dec 29th, 2021
1,210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Highlight map areas as translucent colored blocks. red = circle area, green = poly area, blue = rect area.
  3. Highlight elements have:
  4. - `data-map-name` attribute to indicate the name of the map element.
  5. - `data-area-index` attribute to indicate the zero based index of the area element within map element.
  6. Inspect the highlight element to see the attributes.
  7. */
  8. (() => {
  9.   document.querySelectorAll(`img[usemap^="#"]`).forEach(img => {
  10.     let mapName = img.useMap.substr(1), map;
  11.     if (!(map = document.querySelector(`map${img.useMap},map[name="${mapName}"]`))) return;
  12.     Array.from(map.areas).forEach((area, ai) => {
  13.       let xmin = Infinity, ymin = Infinity, xmax = -Infinity, ymax = -Infinity;
  14.       let coords = area.coords.split(",");
  15.       for (let i = coords.length - 1; i >= 0; i--) {
  16.         coords[i] = parseInt(coords[i]);
  17.         if (i & 1) {
  18.           if (coords[i] > ymax) {
  19.             ymax = coords[i]
  20.           } else if (coords[i] < ymin) ymin = coords[i];
  21.         } else if (coords[i] > xmax) {
  22.           xmax = coords[i]
  23.         } else if (coords[i] < xmin) xmin = coords[i];
  24.       }
  25.       switch (area.shape) {
  26.         case "circle":
  27.           styles = `\
  28. left:${xmin + img.offsetLeft}px;\
  29. top:${ymin + img.offsetTop}px;\
  30. width:${xmax - xmin}px;\
  31. height:${ymax - ymin}px;\
  32. background:red;`;
  33.           break;
  34.         case "poly":
  35.           styles = `\
  36. left:${xmin + img.offsetLeft}px;\
  37. top:${ymin + img.offsetTop}px;\
  38. width:${xmax - xmin}px;\
  39. height:${ymax - ymin}px;\
  40. background:green;`;
  41.           break;
  42.         case "rect":
  43.           styles = `\
  44. left:${coords[0] + img.offsetLeft}px;\
  45. top:${coords[1] + img.offsetTop}px;\
  46. width:${Math.abs(coords[0] - coords[2])}px;\
  47. height:${Math.abs(coords[1] - coords[3])}px;\
  48. background:blue;`;
  49.           break;
  50.         default:
  51.           return;
  52.       }
  53.       let hilite = document.createElement("DIV");
  54.       hilite.dataset.mapName = mapName;
  55.       hilite.dataset.areaIndex = ai;
  56.       hilite.style.cssText = `opacity:0.3;position:absolute;z-index:2;${styles}`;
  57.       img.parentNode.insertBefore(hilite, img);
  58.     });
  59.   });
  60. })();
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement