计算鼠标相对于SVG元素的位置,并列出鼠标下具有相对坐标的元素的SVG元素ID列表

时间:2020-07-04 00:15:54

标签: javascript html jquery css svg

http://jsfiddle.net/t1dj9yv4/

目标确定鼠标相对于其下SVG元素的位置(或更理想地与鼠标/指针事件下的所有元素相关)

理想的输出 相对于整个元素的X / Y坐标和相对于整个SVG图像的X / Y坐标的元素ID列表。

在此示例中,我可以从https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-find-mouse-position-relative-to-an-element那里获取信息

我可以根据ID查找单个元素的坐标或相对于整个图像的坐标(将#Shapes更改为#Poly_1)...

另一个相关示例:SVG - Obtaining ordered list of IDs that appear under mouse/touch hove/click/tap in an SVG http://jsfiddle.net/r9k1bgnu/

将鼠标悬停在SVG的特定区域上时所需输出的示例(我知道第一组坐标在列表中将是相同的,因为它相对于整个图像而言):

Poly 1(Poly1上的指针相对于整个图像的X,Y坐标); (指针相对于Poly1的边界框的X,Y坐标)

Star(相对于整个图像,Star上的指针的X,Y坐标); (指针相对于Star边界框的X,Y坐标)

Gradient_Poly_Large(相对于整个图像,Gradient_Poly_Large上的指针的X,Y坐标); (相对于Gradient_Poly_Large的边界框的指针的X,Y坐标)

Gradient_Star(Gradient_Star上相对于整个图像的指针的X,Y坐标); (指针相对于Gradient_Star的边界框的X,Y坐标)

Green_Square(相对于整个图像,Green_Square上的指针的X,Y坐标); (相对于Green_Square边界框的指针的X,Y坐标)

$(document).ready(function() {
 
 //needs to calculate for all elements, relative to SVG
        $("#Shapes").mousemove(function(event){            
            var relX = event.pageX - $(this).offset().left;
            var relY = event.pageY - $(this).offset().top;
            var relBoxCoords = "(" + relX + "," + relY + ")";
            $(".mouse-cords").text(relBoxCoords);
        });
    
    $("#Poly1").mousemove(function(event){            
        var relX = event.pageX - $(this).offset().left;
        var relY = event.pageY - $(this).offset().top;
        var relBoxCoords = "(" + relX + "," + relY + ")";
        $(".mouse-cords2").text(relBoxCoords);
    });
    
});



(function() {
const svg = document.querySelector('#Shapes'),
      output = document.querySelector('#test');

function printElement(elm) {
    var id = elm.id;
    return id + "(" + "X,Y to replace (will always be same)" + " coordinates of pointer over " + id + " relative to entire image; ("  + "X,Y to replace" + " coordinates of pointer relative to bounding box for " + id + ")" + "<br><br>";
    
}

function hitTest(e) {
    const x = e.clientX,
          y = e.clientY,
          elms = [];

    let elm;
    while(true) {
        elm = document.elementFromPoint(x, y);
        if(!svg.contains(elm)) {
            break;
        }

        elms.push(elm);
        //Hide the element from the next round of `elementFromPoint()`:
        elm.style.pointerEvents = 'none';
    }

    output.textContent = elms.map(printElement).join(' ');

    //Cleanup:
    elms.forEach(elm => elm.style.pointerEvents = '');
}

svg.addEventListener('mousemove', hitTest);
svg.addEventListener('touchmove', hitTest);

})();

如果所需的输出在TOOLTIP中,则更好:)

0 个答案:

没有答案