简体   繁体   English

计算图像地图上多边形区域的宽度和高度

[英]calculate width & height of poly area on image map

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. 我需要找到每个中心点。

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. 要找到中心点,您需要找到多边形的最小和最大X和Y坐标,然后取每个点的中点以获得平均中心点。 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.net/jamietre/6ABfa/ 这里的工作示例将在选定的美国州的中心点画一个圆圈: http//jsfiddle.net/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
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM