首页 > 解决方案 > 基于图像中像素的工具提示

问题描述

我有一组图像。每个图像都显示多个对象。每当我将鼠标指针悬停在图像中的每个对象上时,我都想显示一个工具提示。我有图像中每个对象的像素坐标以及宽度和高度。

我知道为元素实现工具提示的几种不同方法,但不知道如何处理图像内相对于工具提示的像素尺寸。

标签: javascriptjquerybootstrap-4tooltip

解决方案


您可以为此使用图像映射:

var elements = [
 { label: 'Yellow', x: 112, y: 23,  w: 112, h: 89  },
 { label: 'Pink',   x: 27,  y: 119, w: 110, h: 195 },
 { label: 'Brown',  x: 198, y: 124, w: 112, h: 90  }
];

var img = document.querySelector('img'),
    map = document.createElement('map');

map.name = 'my-map';
img.setAttribute('usemap', '#' + map.name);

elements.forEach(function(el) {
  var area = document.createElement('area');
  area.title = el.label;
  area.coords = [el.x, el.y, el.x + el.w, el.y + el.h].join(',');
  map.appendChild(area);
});

document.body.appendChild(map);
<img src="https://image.shutterstock.com/image-photo/three-macaroons-sweet-desserts-isolated-260nw-351030134.jpg">

如果你有多个图像,你可以把它变成一个可重用的函数:

addImageMap(
  document.getElementById('image-a'),
  [
    { label: 'Yellow', x: 112, y: 23,  w: 112, h: 89  },
    { label: 'Pink',   x: 27,  y: 119, w: 110, h: 195 },
    { label: 'Brown',  x: 198, y: 124, w: 112, h: 90  }
  ]
);

addImageMap(
  document.getElementById('image-b'),
  [
    { label: 'Drink',  x: 111, y: 90,  w: 310, h: 450  },
    { label: 'Burger', x: 471, y: 100, w: 320, h: 450 },
    { label: 'Fries',  x: 891, y: 52,  w: 300, h: 450 }
  ]
);

// If you want responsive image maps (see plugin added in HTML)
imageMapResize();

function addImageMap(img, elements) {
  var map = document.createElement('map');

  map.name = 'my-map-' + getUniqueMapId();
  img.setAttribute('usemap', '#' + map.name);

  elements.forEach(function(el) {
    var area = document.createElement('area');
    area.title = el.label;
    area.coords = [el.x, el.y, el.x + el.w, el.y + el.h].join(',');
    map.appendChild(area);
  });

  document.body.appendChild(map);
}

function getUniqueMapId() {
  window.uniqueMapId = (window.uniqueMapId || 0) + 1;
  return window.uniqueMapId;
}
img { width: 200px; }
<!-- Docs: https://github.com/davidjbradshaw/image-map-resizer -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/image-map-resizer/1.0.10/js/imageMapResizer.min.js"></script>

<img id="image-a" src="https://image.shutterstock.com/image-photo/three-macaroons-sweet-desserts-isolated-260nw-351030134.jpg">
<img id="image-b" src="https://previews.123rf.com/images/ifh/ifh1512/ifh151200179/49541375-illustration-of-set-of-three-objects-such-as-hamburger-french-fries-and-coffee.jpg">


推荐阅读