How do I rotate or scale (transform) an SVG path relative to its center point?

后端 未结 3 1316
囚心锁ツ
囚心锁ツ 2020-12-20 23:52

I\'m trying to rotate and scale shapes within an SVG around their center point. I\'ve looked into several libraries, including Jquery, Greensock, D3, RaphaelJS, but I haven\

相关标签:
3条回答
  • 2020-12-21 00:33

    Really its a case of pick the library that suits your needs, and then you will figure a way. As BigBadaboom says, if you do a search, there are lots of solutions.

    To try and combine your questions, as sometimes the tricky bit is using an existing DOM object, I've included an example in Snap.svg. You can often do something similar in most libraries.

    jsfiddle here Fiddle using your existing html.

    s = Snap("#mySVGContainer1");   // create a canvas from existing svg
    
    var triangle1 = s.select("#myShape1").transform("r90"); //select&transform existing object
    
    
    p = Snap("#mySVGContainer2");
    
    var triangle2 = p.select("#myShape2");
    var bbox = triangle2.getBBox(); //bounding box, centre cx/cy
    
    //rotate and scale with transform string (raphael/snap format)
    triangle2.animate({ transform: "r180," + bbox.cx + ',' + bbox.cy + "s3,3," + bbox.cx + "," + bbox.cy }, 2000);  
    
    0 讨论(0)
  • 2020-12-21 00:37

    I've been looking for a long time, and will settle for the following.

    1. Design your svg shape at coordinate x:0,y:0.

    2. Identify by hand the center of rotation, by example, center = [ x:50,y:100].

    3. Build a spinIt() function such :

    function spinIt() {
        needle.transition()
            .duration(2000)
            .attrTween("transform", tween);
        function tween() {
            return d3.interpolateString("rotate(-180, 50, 100)", "rotate(90, 50, 100)");
        }
    }
    

    4. Use it on a triger:

    svg.on("click", spinIt);
    

    http://jsfiddle.net/SHF2M/79/

    0 讨论(0)
  • 2020-12-21 00:40

    For rotations, as @Ian points out, you can specify the center of rotation. For other transformations, changes are defined relative to the path's (0,0) point.

    The easiest way to get transformations to work relative to the path's center is to either:

    1. Define the path so that it is centered around the (0,0) point; or
    2. Wrap the path in a <g> element, and then translate it so it is centered on the (0,0) point of the <g> element's coordinate system.

    Then, you can apply rotations, scales and transforms (on the <g> element, if using) and they will all be nicely centred.

    The trickiest part is figuring out the "center" of an arbitrary shape. @Ian's approach of using the center of the bounding box will usually give decent results. If your shape is a polygon there are d3 functions you could use.

    Example showing a shape moving with the mouse, rotating and changing scale, all centered around the center of the bounding box:
    http://fiddle.jshell.net/LgfE3/

    Edit: simplier jsfiddle

    0 讨论(0)
提交回复
热议问题