Html 响应式图像映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7844399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:11:32  来源:igfitidea点击:

Responsive image map

htmlcssimagemap

提问by jdog

I have an existing image map in a responsive html layout. Images scale according to browser size, but the image coordinates are obviously fixed pixel sizes. What options do I have to resize the image map coordinates?

我在响应式 html 布局中有一个现有的图像映射。图片根据浏览器大小缩放,但图片坐标显然是固定的像素大小。我有哪些选项可以调整图像地图坐标的大小?

采纳答案by Tom

For responsive image maps you will need to use a plugin:

对于响应式图像地图,您需要使用插件:

https://github.com/stowball/jQuery-rwdImageMaps(No longer maintained)

https://github.com/stowball/jQuery-rwdImageMaps(不再维护)

Or

或者

https://github.com/davidjbradshaw/imagemap-resizer

https://github.com/davidjbradshaw/imagemap-resizer



No major browsers understand percentage coordinates correctly, and all interpret percentage coordinates as pixel coordinates.

没有主流浏览器正确理解百分比坐标,所有浏览器都将百分比坐标解释为像素坐标。

http://www.howtocreate.co.uk/tutorials/html/imagemaps

http://www.howtocreate.co.uk/tutorials/html/imagemaps

And also this page for testing whether browsers implement

还有这个用于测试浏览器是否实现的页面

http://home.comcast.net/~urbanjost/IMG/resizeimg3.html

http://home.comcast.net/~urbanjost/IMG/resizeimg3.html

回答by belgac

You can also use svg instead of an image map. ;)

您还可以使用 svg 代替图像映射。;)

There is a tutorial on how to do this.

有一个关于如何做到这一点的教程

.hover_group:hover {
  opacity: 1;
}
#projectsvg {
  position: relative;
  width: 100%;
  padding-bottom: 77%;
  vertical-align: middle;
  margin: 0;
  overflow: hidden;
}
#projectsvg svg {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
}
<figure id="projectsvg">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1920 1080" preserveAspectRatio="xMinYMin meet" >
<!-- set your background image -->
<image width="1920" height="1080" xlink:href="http://placehold.it/1920x1080" />
<g class="hover_group" opacity="0">
  <a xlink:href="https://example.com/link1.html">
    <text x="652" y="706.9" font-size="20">First zone</text>
    <rect x="572" y="324.1" opacity="0.2" fill="#FFFFFF" width="264.6" height="387.8"></rect>
  </a>
</g>
<g class="hover_group" opacity="0">
  <a xlink:href="https://example.com/link2.html">
    <text x="1230.7" y="952" font-size="20">Second zone</text>
    <rect x="1081.7" y="507" opacity="0.2" fill="#FFFFFF" width="390.2" height="450"></rect>
  </a>
</g>
  </svg>
</figure>

回答by Joshua Stewardson

回答by Jeffrey Langham

I ran across a solution that doesn't use image maps at all but rather anchor tags that are absolutely positioned over the image. The only drawback would be that the hotspot would have to be rectangular, but the plus is that this solution doesn't rely on Javascript, just CSS. There is a website that you can use to generate the HTML code for the anchors: http://www.zaneray.com/responsive-image-map/

我遇到了一个根本不使用图像映射而是使用绝对定位在图像上的锚标记的解决方案。唯一的缺点是热点必须是矩形的,但优点是该解决方案不依赖于 Javascript,只依赖于 CSS。有一个网站可用于为锚点生成 HTML 代码:http: //www.zaneray.com/responsive-image-map/

I put the image and the generated anchor tags in a relatively positioned div tag and everything worked perfectly on window resize and on my mobile phone.

我将图像和生成的锚标签放在一个相对定位的 div 标签中,一切都在调整窗口大小和我的手机上完美运行。

回答by Tom Bisciglia

I found a no-JS way to address this if you are okay with rectangular hit areas.

如果您对矩形命中区域没问题,我找到了一种无 JS 方法来解决这个问题。

First of all, make sure your image is in a div that's relatively positioned. Then put the image inside this div, which means it'll take up all the space in the div. Finally, add absolutely positioned div's under the image, within the main div, and use percentages for top, left, width, and height to get the link hit areas the size and position you want.

首先,确保您的图像位于相对定位的 div 中。然后把图片放在这个 div 里面,这意味着它会占用 div 中的所有空间。最后,在图像下方的主 div 内添加绝对定位的 div,并使用顶部、左侧、宽度和高度的百分比来获得所需的链接命中区域的大小和位置。

I find it's easiest to give the div a black background color (ideally with some alpha fading so you can see the linked content underneath) when you're first working, and to use a code inspector in your browser to adjust the percentages in real time, so that you can get it just right.

我发现当你第一次工作时,给 div 一个黑色的背景颜色(最好有一些 alpha 淡入淡出,这样你就可以看到下面的链接内容)是最简单的,并在浏览器中使用代码检查器实时调整百分比,以便您可以恰到好处。

Here's the basic outline you can work with. By doing everything with percentages, you ensure the elements all stay the same relative size and position as the image scales.

这是您可以使用的基本大纲。通过使用百分比做所有事情,您可以确保元素在图像缩放时保持相同的相对大小和位置。

<div style="position: relative;">
  <img src="background-image.png" style="width: 100%; height: auto;">
  <a href="/link1"><div style="position: absolute; left: 15%; top: 20%; width: 12%; height: 8%; background-color: rgba(0, 0, 0, .25);"></div></a>
  <a href="/link2"><div style="position: absolute; left: 52%; top: 38%; width: 14%; height: 20%; background-color: rgba(0, 0, 0, .25);"></div></a>
</div>

Use this code with your code inspector in Chrome or your browser of choice, and adjust the percentages (you can use decimal percentages to be more exact) until the boxes are just right. Also choose a background-colorof transparentwhen you're ready to use it since you want your hit areas to be invisible.

将此代码与 Chrome 中的代码检查器或您选择的浏览器一起使用,并调整百分比(您可以使用小数百分比更准确),直到框恰到好处。也可选择background-colortransparent,当你准备,因为你希望你的命中地区是不可见的使用它。

回答by Grodriguez

David Bradshaw wrote a nice little library that solves this problem. It can be used with or without jQuery.

David Bradshaw 写了一个很好的小库来解决这个问题。它可以在有或没有 jQuery 的情况下使用。

Available here: https://github.com/davidjbradshaw/imagemap-resizer

可在此处获得:https: //github.com/davidjbradshaw/imagemap-resizer

回答by chimeraha

The following method works perfectly for me, so here's my full implementation:

以下方法非常适合我,所以这是我的完整实现:

<img id="my_image" style="display: none;" src="my.png" width="924" height="330" border="0" usemap="#map" />

<map name="map" id="map">
    <area shape="poly" coords="774,49,810,21,922,130,920,222,894,212,885,156,874,146" href="#mylink" />
    <area shape="poly" coords="649,20,791,157,805,160,809,217,851,214,847,135,709,1,666,3" href="#myotherlink" />
</map>

<script>
$(function(){
    var image_is_loaded = false;
    $("#my_image").on('load',function() {
        $(this).data('width', $(this).attr('width')).data('height', $(this).attr('height'));
        $($(this).attr('usemap')+" area").each(function(){
            $(this).data('coords', $(this).attr('coords'));
        });

        $(this).css('width', '100%').css('height','auto').show();

        image_is_loaded = true;
        $(window).trigger('resize');
    });


    function ratioCoords (coords, ratio) {
        coord_arr = coords.split(",");

        for(i=0; i < coord_arr.length; i++) {
            coord_arr[i] = Math.round(ratio * coord_arr[i]);
        }

        return coord_arr.join(',');
    }
    $(window).on('resize', function(){
        if (image_is_loaded) {
            var img = $("#my_image");
            var ratio = img.width()/img.data('width');

            $(img.attr('usemap')+" area").each(function(){
                console.log('1: '+$(this).attr('coords'));
                $(this).attr('coords', ratioCoords($(this).data('coords'), ratio));
            });
        }
    });
});
</script>

回答by Rahul Mahadik

I come across with same requirement where, I wants to show responsive image map which can resize with any screen size and important thing is, i want to highlight that coordinates.

我遇到了同样的要求,我想显示可以随任何屏幕尺寸调整大小的响应式图像地图,重要的是,我想突出显示该坐标

So i tried many libraries which can resize coordinates according to screen size and event. And i got best solution(jquery.imagemapster.min.js) which works fine with almost all browsers. Also i have integrated it with Summer Plginwhich create image map.

所以我尝试了许多可以根据屏幕大小和事件调整坐标大小的库。我得到了最好的解决方案(jquery.imagemapster.min.js),它几乎适用于所有浏览器。我还将它与创建图像映射的Summer Plgin集成在一起。

 var resizeTime = 100;
 var resizeDelay = 100;    

$('img').mapster({
        areas: [
            {
                key: 'tbl',
                fillColor: 'ff0000',
                staticState: true,
                stroke: true
            }
        ],
        mapKey: 'state'
    });

    // Resize the map to fit within the boundaries provided

    function resize(maxWidth, maxHeight) {
        var image = $('img'),
            imgWidth = image.width(),
            imgHeight = image.height(),
            newWidth = 0,
            newHeight = 0;

        if (imgWidth / maxWidth > imgHeight / maxHeight) {
            newWidth = maxWidth;
        } else {
            newHeight = maxHeight;
        }
        image.mapster('resize', newWidth, newHeight, resizeTime);
    }

    function onWindowResize() {

        var curWidth = $(window).width(),
            curHeight = $(window).height(),
            checking = false;
        if (checking) {
            return;
        }
        checking = true;
        window.setTimeout(function () {
            var newWidth = $(window).width(),
                newHeight = $(window).height();
            if (newWidth === curWidth &&
                newHeight === curHeight) {
                resize(newWidth, newHeight);
            }
            checking = false;
        }, resizeDelay);
    }

    $(window).bind('resize', onWindowResize);
img[usemap] {
        border: none;
        height: auto;
        max-width: 100%;
        width: auto;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.imagemapster.min.js"></script>

<img src="https://discover.luxury/wp-content/uploads/2016/11/Cities-With-the-Most-Michelin-Star-Restaurants-1024x581.jpg" alt="" usemap="#map" />
<map name="map">
    <area shape="poly" coords="777, 219, 707, 309, 750, 395, 847, 431, 916, 378, 923, 295, 870, 220" href="#" alt="poly" title="Polygon" data-maphilight='' state="tbl"/>
    <area shape="circle" coords="548, 317, 72" href="#" alt="circle" title="Circle" data-maphilight='' state="tbl"/>
    <area shape="rect" coords="182, 283, 398, 385" href="#" alt="rect" title="Rectangle" data-maphilight='' state="tbl"/>
</map>

Hope help it to someone.

希望对某人有所帮助。

回答by Niente0

Working for me (remember to change 3 things in code):

为我工作(记住在代码中更改 3 件事):

  • previousWidth (original size of image)

  • map_ID (id of your image map)

  • img_ID (id of your image)

  • previousWidth(图像的原始大小)

  • map_ID(您的图像地图的 ID)

  • img_ID(你的图片ID)

HTML:

HTML:

<div style="width:100%;">
    <img id="img_ID" src="http://www.gravatar.com/avatar/0865e7bad648eab23c7d4a843144de48?s=128&d=identicon&r=PG" usemap="#map" border="0" width="100%" alt="" />
</div>
<map id="map_ID" name="map">
<area shape="poly" coords="48,10,80,10,65,42" href="javascript:;" alt="Bandcamp" title="Bandcamp" />
<area shape="poly" coords="30,50,62,50,46,82" href="javascript:;" alt="Facebook" title="Facebook" />
<area shape="poly" coords="66,50,98,50,82,82" href="javascript:;" alt="Soundcloud" title="Soundcloud" />
</map>

Javascript:

Javascript:

window.onload = function () {
    var ImageMap = function (map, img) {
            var n,
                areas = map.getElementsByTagName('area'),
                len = areas.length,
                coords = [],
                previousWidth = 128;
            for (n = 0; n < len; n++) {
                coords[n] = areas[n].coords.split(',');
            }
            this.resize = function () {
                var n, m, clen,
                    x = img.offsetWidth / previousWidth;
                for (n = 0; n < len; n++) {
                    clen = coords[n].length;
                    for (m = 0; m < clen; m++) {
                        coords[n][m] *= x;
                    }
                    areas[n].coords = coords[n].join(',');
                }
                previousWidth = img.offsetWidth;
                return true;
            };
            window.onresize = this.resize;
        },
        imageMap = new ImageMap(document.getElementById('map_ID'), document.getElementById('img_ID'));
    imageMap.resize();
    return;
}

JSFiddle: http://jsfiddle.net/p7EyT/154/

JSFiddle:http: //jsfiddle.net/p7EyT/154/

回答by Travis Clarke

Check out the image-mapplugin on Github. It works both with vanilla JavaScript and as a jQuery plugin.

查看Github 上的图像映射插件。它适用于 vanilla JavaScript 和 jQuery 插件。

$('img[usemap]').imageMap();     // jQuery

ImageMap('img[usemap]')          // JavaScript

Check out the demo.

查看演示