Reputation: 43833
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>
Upvotes: 3
Views: 4043
Reputation: 3199
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.
Upvotes: 3
Reputation: 426
SVG elements do not share all of the CSS and JavaScript functionality that normal HTML elements do. There are some CSS properties that work differently on SVG elements, and some that don't work at all.
For this task, you can use the transform
attribute on the right_arm
element, and specify a rotation. The syntax is like this:
rotate(<a> [<x> <y>])
where <a>
is the angle, and <x> <y>
is an option (x,y) coordinate. In your example, if you want to rotate right_arm
90 degrees, you would do:
right_arm.setAttribute("transform", "rotate(90)");
transform
does not work on all SVG elements, however. For more information on this, I would suggest looking at this page.
Upvotes: 0