Mouse position inside autoscaled SVG

前端 未结 3 585
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 06:00

I am experiencing troubles concerning the position of mouse cursor inside my SVG document. I\'d like to design a potentiometer that will follow the cursor when dragged, usin

3条回答
  •  执笔经年
    2020-12-02 06:43

    Getting the correct svg mouse coordinate is tricky. First of all, a common way is to use the clientX and clientY of the event property an substract it with getBoundingClientRect() and clientLeft respectively clientTop.

    svg.addEventListener('click', event =>
    {
        let bound = svg.getBoundingClientRect();
    
        let x = event.clientX - bound.left - svg.clientLeft - paddingLeft;
        let y = event.clientY - bound.top - svg.clientTop - paddingTop;
    }
    

    But, if the svg has a padding style information greater then zero, the coordinate is shifting. So this information must be also substract:

    let paddingLeft = parseFloat(style['padding-left'].replace('px', ''));
    let paddingTop = parseFloat(style['padding-top'].replace('px', ''));
    
    let x = event.clientX - bound.left - svg.clientLeft - paddingLeft;
    let y = event.clientY - bound.top - svg.clientTop - paddingTop;
    

    And the not so nice think is, that in some browsers the border property also shift the coordinate, and in other not. I found out, that the shift takes place if the x and y of the event property is not available.

    if(event.x === undefined)
    {
        x -= parseFloat(style['border-left-width'].replace('px', ''));
        y -= parseFloat(style['border-top-width'].replace('px', ''));
    }
    

    After this transformation the x and y coordinate can out of bound, that should be fix. But that not the think.

    let width = svg.width.baseVal.value;
    let height = svg.height.baseVal.value;
    
    if(x < 0 || y < 0 || x >= width || y >= height)
    {
        return;
    }
    

    This solution can use for click, mousemove, mousedown, ... and so on. You can reach a live demo here: https://codepen.io/martinwantke/pen/xpGpZB

提交回复
热议问题