javascript 带有 SVG 的 JS:围绕其中心旋转 SVG 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20515576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:40:34  来源:igfitidea点击:

JS with SVG: Rotate SVG-Element around its center

javascriptsvgrotation

提问by sumisu

I have to rotate three SVG-Objects around its center with JavaScript and not the <animation>tag. The big star at the top of the tree rotates correctly, but from the others I don't find the center coordinates.

我必须使用 JavaScript 而不是<animation>标签围绕其中心旋转三个 SVG 对象。树顶的大星星正确旋转,但从其他星星我找不到中心坐标。

This is the second star and the rotation in JS:

这是JS中的第二颗星和旋转:

star2.setAttribute("transform", "rotate(" + angle + " 2000 200)");

and this is the svg:

这是 svg:

<defs>
    <symbol id="stern">
        <polygon points="1000 50 1100 310 850 160 1150 160 900 310 1000 50" fill="yellow" />
    </symbol>
</defs>

<use id="stern2" xlink:href="#stern" transform="translate(500,600) scale(0.5)" onmouseover="rotate2();" onmouseout="stop();" />

Here is a fiddle:

这是一个小提琴:

http://jsfiddle.net/F325k/

http://jsfiddle.net/F325k/

回答by Markus

to rotate around the center you need to translate it first: Rotate rectangle around its own center in SVG

要围绕中心旋转,您需要先平移它:在 SVG 中围绕其自身中心旋转矩形

ps: the latest and reworked lib from the author of Rapha?l is http://snapsvg.io/in case you can use one.

ps:Rapha?l 的作者最新的和重新设计的库是http://snapsvg.io/,以防你可以使用。

回答by ambodi

For SVG, definately use third-party libraries. SVG is a pain with plain javascript. My suggestion: Definately go for D3js, I have been using it for a year at my workplace and it is great: dynamic, good community, brilliant documentation.

对于 SVG,一定要使用第三方库。SVG 是一个痛苦的纯 javascript。我的建议:绝对D3js,我已经在我的工作场所使用它一年了,它很棒:动态,良好的社区,出色的文档。

See the following example with spinning circle around its center which is called Planetarium: PlanetariumDoes the rotation without animation as you wanted. It uses a D3- timer and that is all.

请参阅以下示例,其中围绕其中心旋转的圆圈称为天文馆:天文馆根据您的需要在没有动画的情况下进行旋转。它使用 D3 计时器,仅此而已。

There are a lot of examples there, so read the full example list here: d3js Full list of examples

那里有很多示例,因此请在此处阅读完整的示例列表:d3js Full list of examples