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

后端 未结 3 1348
囚心锁ツ
囚心锁ツ 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条回答
  •  猫巷女王i
    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 element, and then translate it so it is centered on the (0,0) point of the element's coordinate system.

    Then, you can apply rotations, scales and transforms (on the 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

提交回复
热议问题