javascript - 基于图像中像素的工具提示
问题描述
我有一组图像。每个图像都显示多个对象。每当我将鼠标指针悬停在图像中的每个对象上时,我都想显示一个工具提示。我有图像中每个对象的像素坐标以及宽度和高度。
我知道为元素实现工具提示的几种不同方法,但不知道如何处理图像内相对于工具提示的像素尺寸。
解决方案
您可以为此使用图像映射:
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">
推荐阅读
- python - 如何使用 tweepy 检索全文推文?
- mysql - 无法在 MySQL 事件调度程序正文中打开 SQL 脚本
- javascript - 即使样式隐藏,引导程序也保持 4 pic 一致
- javascript - 在 HTML5 输入字段的文本前添加键入数字的最佳方法?
- sinon - 带有ExactArgs的Sinon存根?
- c# - WPF CroppedBitmap + RenderTargetBitmap = EventHandler 泄漏问题和冻结问题
- python - 自动化 MKS 完整性的有效脚本选项
- java - 在双向多对多关系中高效获取子/父实体
- javascript - 画布 getImageData 但按比例缩小
- spring - Spring 集成 Java DSL SFTP 异常处理