How to get the click coordinates relative to SVG element holding the onclick listener?

前端 未结 3 1019
萌比男神i
萌比男神i 2020-12-25 11:37

I haven\'t been able to calculate the click coordinates (x and y) relative to the element triggering the event. I have not found an easy example online.

I have a sim

3条回答
  •  我在风中等你
    2020-12-25 12:08

    Tolokoban's solution has the limitation that it doesn't work if your viewBox deviates from the default, that is if it is different from viewBox="0 0 width height". A better solution that also takes viewBox into account is this:

    var pt = svg.createSVGPoint();  // Created once for document
    
    function alert_coords(evt) {
        pt.x = evt.clientX;
        pt.y = evt.clientY;
    
        // The cursor point, translated into svg coordinates
        var cursorpt =  pt.matrixTransform(svg.getScreenCTM().inverse());
        console.log("(" + cursorpt.x + ", " + cursorpt.y + ")");
    }
    

    (Credit goes to Smerk, who posted the code)

    If the viewBox is not set or set to the default, this script will return the same values as Tolokoban's script. But if you have an SVG like , only this version will give you the correct results.

提交回复
热议问题