SVG coordinates with transform matrix

后端 未结 2 1945
有刺的猬
有刺的猬 2020-11-28 03:00

I want to implement the functionality like svg-edit on rectangle element

  1. Rotate rectangle
  2. Resizing
  3. Drag

Rotating the SVG rec

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 03:17

    I have created a working example of what I believe you are describing on my site here:
    http://phrogz.net/svg/drag_under_transformation.xhtml

    In general, you convert the mouse cursor into the local space of an object by:

    1. Creating a mousemove event handler:

      var svg = document.getElementsByTagName('svg')[0];
      document.documentElement.addEventListener('mousemove',function(evt){
        ...
      },false);
      
    2. In that event handler, convert the mouse coordinates (in pixels) into the global space of your SVG document:

      var pt = svg.createSVGPoint();
      pt.x = evt.clientX;
      pt.y = evt.clientY;
      var globalPoint = pt.matrixTransform(svg.getScreenCTM().inverse());
      
    3. Convert the global point into the space of the object you are dragging:

      var globalToLocal = dragObject.getTransformToElement(svg).inverse();
      var inObjectSpace = globalPoint.matrixTransform( globalToLocal );
      

    For Stack Overflow posterity, here's the full source of my SVG+XHTML demo (in case my site is down):

    
     
    
    Dragging Transformed SVG Elements
    
    
    

    Showing how to drag points inside a transformation hierarchy.

提交回复
热议问题