Mouse position inside autoscaled SVG

前端 未结 3 601
爱一瞬间的悲伤
爱一瞬间的悲伤 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:27

    See this code, which not only shows how to transform from screen space to global SVG space, but also how to transform a point from SVG space into the transformed space of an element:
    http://phrogz.net/svg/drag_under_transformation.xhtml

    In short:

    // Find your root SVG element
    var svg = document.querySelector('svg');
    
    // Create an SVGPoint for future math
    var pt = svg.createSVGPoint();
    
    // Get point in global SVG space
    function cursorPoint(evt){
      pt.x = evt.clientX; pt.y = evt.clientY;
      return pt.matrixTransform(svg.getScreenCTM().inverse());
    }
    
    svg.addEventListener('mousemove',function(evt){
      var loc = cursorPoint(evt);
      // Use loc.x and loc.y here
    },false);
    

    Edit: I've created a sample tailored to your needs (albeit only in global SVG space):
    http://phrogz.net/svg/rotate-to-point-at-cursor.svg

    It adds the following method to the above:

    function rotateElement(el,originX,originY,towardsX,towardsY){
      var angle = Math.atan2(towardsY-originY,towardsX-originX);
      var degrees = angle*180/Math.PI + 90;
      el.setAttribute(
        'transform',
        'translate('+originX+','+originY+') ' +
          'rotate('+degrees+') ' +
          'translate('+(-originX)+','+(-originY)+')'
      );
    }
    

提交回复
热议问题