最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Resize image map on window resize - Stack Overflow

programmeradmin9浏览0评论

I'm trying to resize an image map on window resize event. The closest I've gotten is to use a mouseclick event, but it needs to be window resize for what I'm doing. I'm using Firefox 3.5.5

I'm using jquery somewhat. Here's my example - the area button I want to resize on window resize is in the top left (click on it to resize map and area button):

.html

Any help would be appreciated! Thank you, Rich

I'm trying to resize an image map on window resize event. The closest I've gotten is to use a mouseclick event, but it needs to be window resize for what I'm doing. I'm using Firefox 3.5.5

I'm using jquery somewhat. Here's my example - the area button I want to resize on window resize is in the top left (click on it to resize map and area button):

http://www.whitebrickstudios.com/foghornstour/imagemap3.html

Any help would be appreciated! Thank you, Rich

Share Improve this question asked Nov 30, 2009 at 18:57 KozyKozy 2,8413 gold badges21 silver badges11 bronze badges 2
  • You've a typo in imageMapResize maybe. You say scaleXY('theMap' when I think you meant scaleXY('myimage'? – Crescent Fresh Commented Nov 30, 2009 at 19:04
  • github.com/davidjbradshaw/image-map-resizer – Blazemonger Commented Jul 3, 2017 at 18:14
Add a comment  | 

8 Answers 8

Reset to default 5

I wrote some simple function to rebuild all map points on every event. Try this

function mapRebuild(scaleValue) {
    var map = $("#imgmap"); // select your map or for all map you can choose $("map").each(function() { map = $(this);.....})
    map.find("area").each(function() { // select all areas
        var coords = $(this).attr("coords"); // extract coords
            coords = coords.split(","); // split to array
        var scaledCoords = "";
        for (var coord in coords) { // rebuild all coords with scaleValue
              scaledCoords += Math.floor(coords[coord] * scaleValue) + ",";
            }
        scaledCoords = scaledCoords.slice(0, -1); // last coma delete
        $(this).attr("coords", scaledCoords); // set new coords
        });
    }

scaleValue can be calculated as oldWindowWidth/newWindowWidth. Of course you need to keep the value of oldWindowWidth on window resize. Maybe my solution not on time, but i hope this is useful to someone

I think what you want is at http://home.comcast.net/~urbanjost/semaphore.html

where I show different examples of how to make your image map coordinates change when your image display size changes.

This is an old thread but for anyone looking for a solution for a similar or even identical problem, the ImageMapster jQuery plugin appears to provide the easiest solution. You can use its resize method (which can even animate the resizing if desired!) as follows to resize an image along with its image map:

$('img').mapster( 'resize', newWidth, newHeight, resizeTime);

You can find a link on ImageMapster's demo page to a jsFiddle that demonstrates resizing an image & its map in response to changing the browser window.

As a modified version of Viktor's answer, this version can handle multiple resizes. It stores initial values for comparison against any future resize. This also uses waitForFinalEvent so it doesn't run over and over on resize.



    var mapImg = $('#mapImg');
    var naturalWidth = 1200; // set manually to avoid ie8 issues
    var baseAreas = new Array();
    var scaleValue = mapImg.width() / naturalWidth;

    $(window).resize( function() {
        waitForFinalEvent( function() {
            scaleValue = mapImg.width() / naturalWidth;
            mapRebuild( scaleValue );
        }, 500, 'resize-window');
    });

    function mapRebuild( scaleValue ) {
        var map = $("#imgMap");
        var mapareas = map.find( 'area' );
        if ( baseAreas.length == 0 ) {
            mapareas.each( function() {
                baseAreas.push( $(this).attr( 'coords' ) ); // set initial values
            });
        }
        mapareas.each( function( index ) {
            var coords = baseAreas[index]; // use the corresponding base coordinates        
            coords = coords.split( ',' );       
            var scaledCoords = '';
            for ( var coord in coords ) {
                scaledCoords += Math.floor( coords[coord] * scaleValue ) + ',';
            }
            scaledCoords = scaledCoords.slice( 0, -1 );
            $(this).attr( 'coords', scaledCoords );
        });
    }

    mapRebuild( scaleValue ); // initial scale

Here is a solution that does not use jQuery.

First, build a library function:

var ImageMap = {
    resize: function(coords, mapWidth) {
        var areas = document.getElementsByTagName('area'),
            imageWidth = document.querySelector("#map").clientWidth,
            resize = imageWidth / mapWidth;

        for (var i=0; i<coords.length; i++) {
            var temp = coords[i].map(x=>Math.round(x*resize));
            areas[i].coords = temp.join(',');
        }
    },
    getCoords: function(){
        var areas = document.getElementsByTagName('area'),
            array = [];
        for (var i=0; i<areas.length; i++) {
            array.push(areas[i].coords.split(',').map(x=>+x));
        }
        return array;
    }
};

Then, call the resize function when the page is initially loaded, and when it is resized:

var coords = ImageMap.getCoords();
window.onload = function () {
    ImageMap.resize(coords, 500);
}
window.onresize = function () {
    ImageMap.resize(coords, 500);
}

Replace 500 with whatever your default map size is

a concret sample to recalculate coords of image map when window is loaded or resized:

this image is 1930 * 3360 :

  <div>
    <img id = "alhambra" src="filename.png" usemap="#image-map" width=100%>

    <map name="image-map">
        <area target="" alt="home" id = "home" title="home" href="" coords="1905,307,35,12" shape="rect">
        <area target="" alt="vaciado" id = "vaciado" title="vaciado" href="" coords="141,367,1783,631" shape="rect">
        <area target="" alt="tienda" id = "tienda" title="tienda" href="" coords="282,1408,278" shape="circle">
        <area target="" alt="stocks" id = "stocks" title="stocks" href="" coords="1300,2968,722,2699" shape="rect">
        <area target="" alt="whatsapp" id = "whatsapp" title="whatsapp" href="" coords="506,2980,1788,3193" shape="rect">
        <area target="" alt="direccion" id = "direccion" title="direccion" href="" coords="43,3215,1883,3324" shape="rect">
    </map>
  </div>

and add the script after body as:

</body>
<script>
  let text_home_coord = document.getElementById('home').coords;
  let text_vaciado_coord = document.getElementById('vaciado').coords;
  let text_tienda_coord = document.getElementById('tienda').coords;
  let text_stocks_coord = document.getElementById('stocks').coords;
  let text_whatsapp_coord = document.getElementById('whatsapp').coords;
  let text_direccion_coord = document.getElementById('direccion').coords;
  
  function img_map_response(){

    // get width and height in pixel
  var width_100_in_px = document.getElementById('alhambra').offsetWidth;
  var height_100_in_px = document.getElementById('alhambra').offsetHeight;

  // recalculate coords of image map
  function get_coor_resp(nombre_coords){

    // real width and height of image map
    var img_real_width="1930";
    var img_real_height="3360";

    // convert string coords to array
    text_array = nombre_coords.split(',');

    // rect
    if (text_array.length == 4) {
      // convert strig to integer
      x1 = parseInt(parseInt(text_array[0])*parseInt(width_100_in_px)/parseInt(img_real_width));
      y1 = parseInt(parseInt(text_array[1])*parseInt(height_100_in_px)/parseInt(img_real_height));
      x2 = parseInt(parseInt(text_array[2])*parseInt(width_100_in_px)/parseInt(img_real_width));
      y2 = parseInt(parseInt(text_array[3])*parseInt(height_100_in_px)/parseInt(img_real_height));
      // result converted in array of strings
      array_txt =[x1.toString(), y1.toString(), x2.toString(), y2.toString()]
      console.log("array_txt",array_txt)
      return array_txt.join(',')

    // circle
    } else {
      // convert strig to integer
      x1 = parseInt(parseInt(text_array[0])*parseInt(width_100_in_px)/parseInt(img_real_width));
      y1 = parseInt(parseInt(text_array[1])*parseInt(height_100_in_px)/parseInt(img_real_height));
      r = parseInt(parseInt(text_array[2])*parseInt(width_100_in_px)/parseInt(img_real_width));
      // result converted in array of strings
      array_txt =[x1.toString(), y1.toString(), r.toString()]
      return array_txt.join(',')        
    }
  }
  
 // set coords by recalculate coords (converted in string)
  document.getElementById('home').coords=get_coor_resp(text_home_coord);
  document.getElementById('vaciado').coords=get_coor_resp(text_vaciado_coord);
  document.getElementById('tienda').coords=get_coor_resp(text_tienda_coord);
  document.getElementById('stocks').coords=get_coor_resp(text_stocks_coord);
  document.getElementById('whatsapp').coords=get_coor_resp(text_whatsapp_coord);
  document.getElementById('direccion').coords=get_coor_resp(text_direccion_coord);
}
// add events load and resize for recalculate coords
window.addEventListener('load', img_map_response);
window.addEventListener('resize', img_map_response);
</script>

</html>

To call a function when the window is resized, try the following:

$(window).bind('resize', function() {
    // resize the button here
});

Also, line 37 is missing a dollar sign:

scaleXY('theMap',(window).width());

It should be:

scaleXY('theMap',$(window).width());

If you only need to resize the image, use this technique: http://www.cssplay.co.uk/layouts/background.html

Thanks to CSSPlay.

发布评论

评论列表(0)

  1. 暂无评论