【问题标题】:calculate width & height of poly area on image map计算图像地图上多边形区域的宽度和高度
【发布时间】:2013-03-18 12:43:08
【问题描述】:

是否可以使用坐标计算图像地图上每个多边形区域的宽度和高度?

我有一个图像并使用具有多个不同大小多边形的图像映射。我需要找到每个中心点。

【问题讨论】:

    标签: javascript image imagemap


    【解决方案1】:

    要找到中心点,需要找到多边形的最小和最大X和Y坐标,然后取各自的中点,得到平均中心点。这是一个函数,它将为一组图像映射区域执行此操作。该函数接受一个数组而不是一个区域,以防您需要来自多个区域的中心点,这在地理图像地图中很常见。

    此处的工作示例将在所选美国州的中心点绘制一个圆圈: 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
        };
    }
    

    【讨论】:

    • @jamie-treworgy 如果想在一个循环中分别获得多个区域的中心,我需要更改什么。假设我有适用于 5 个州的条件。现在我想在页面加载时标记这些状态。谢谢。
    • 完美~!谢谢。
    猜你喜欢
    • 2019-05-31
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多