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

javascript - calculate width & height of poly area on image map - Stack Overflow

programmeradmin8浏览0评论

Is it possible to calculate width and height for each poly area on image map using coords?

I have an image and use image map with multiple different sized polys. I need to find center point each one.

Is it possible to calculate width and height for each poly area on image map using coords?

I have an image and use image map with multiple different sized polys. I need to find center point each one.

Share Improve this question edited Mar 18, 2013 at 16:00 Jamie Treworgy 24.4k9 gold badges80 silver badges119 bronze badges asked Mar 18, 2013 at 12:43 Salt HareketSalt Hareket 7647 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

To find the center point, you need to find the minimum and maximum X and Y coordinates of the polygon, and then take the midpoint of each to get the average center point. Here's a function that will do this for an array of imagemap areas. The function accepts an array rather than just one area in case you need a center point from several areas, as are typical in geographical image maps.

Working example here that will draw a circle on the center point of the chose US state: http://jsfiddle/jamietre/6ABfa/

/* Calculate the centermost point of an array of areas 
   @param {element[]}   areas     an array of area elements
   @returns {object}              {x,y} coords of the center point
 */

function calculateCenterPoint(areas) {
    var maxX = 0,
        minX = Infinity,
        maxY = 0,
        minY = Infinity;

   // note: using Array.prototype.forEach instead of calling forEach directly 
   // on "areas" so it will work with array-like objects, e.g. jQuery

    Array.prototype.forEach.call(areas, function (e) {
        var i = 0,
            coords = e.getAttribute('coords').split(',');

        while (i < coords.length) {
            var x = parseInt(coords[i++],10),
                y = parseInt(coords[i++],10);

            if (x < minX) minX = x;
            else if (x > maxX) maxX = x;

            if (y < minY) minY = y;
            else if (y > maxY) maxY = y;
        }
    });

    return {
        x: minX + (maxX - minX) / 2,
        y: minY + (maxY - minY) / 2
    };
}
发布评论

评论列表(0)

  1. 暂无评论