Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply transformation to svg path element?

Tags:

javascript

svg

In my html file, I load an svg image and select one of its path elements. Now I want to rotate it, but I don't know how. The below code does not work.

Does anyone know how to do this?

Thanks

<!DOCTYPE html>
<html>
    <head>
        <title>Animate</title>
        <style>
        </style>
        <script src="../js/plugin/jquery-2.1.4.min.js"></script>
    </head>
    <body>

        <object data="images/steve/steve.svg" type="image/svg+xml" id="steve" width="100%" height="100%"></object>

        <script>
            var steve = document.getElementById("steve");

            steve.addEventListener("load", function() {


                var svgDoc = steve.contentDocument; 
                var right_arm = svgDoc.getElementById("right_arm"); 



                //right_arm.rotate(90);    // THIS DOES NOT WORK


            },false);

        </script>
    </body>

</html> 
like image 906
omega Avatar asked Sep 08 '25 07:09

omega


1 Answers

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform

You have to set a transform attribute directly on your SVG element. The rotate method takes a required argument which is the number of degrees you want to rotate your element.

right_arm.setAttribute('transform','rotate(45)');

You have to use the .setAttribute(...) method in javascript because if you were to do this in your HTML directly, you would literally specify attributes directly to the DOM element itself:

<rect transform="rotate(45)" ... />

http://www.w3.org/TR/SVG/coords.html#TransformAttribute

It's important to note that per the SVG specifications, you are only allowed certain attributes to your SVG elements. Take a look at all of the attributes applicable for the rect element, for example http://www.w3.org/TR/SVG/shapes.html#RectElement.

like image 154
Danny Bullis Avatar answered Sep 10 '25 08:09

Danny Bullis