4

So, I'm using snap.svg and I'd like to dynamically rotate an object over time. Something like this:

function rotateObject()
{
    myObject.rotation += value;
}

The problem is I don't know how to access the rotation values for my display objects (or if they even exist!) So given something simple, let's say a circle declared like this:

snap = Snap(800,600);   
circle = snap.circle(400,300,50);

I know I can access the x and y values like so:

circle.attr("cx");
circle.attr("cy");

What I need help with is:

  1. Is there a rotation property of some sort that I can use to rotate this object?
  2. If not, how do I rotate an object with snap.svg?
Paul Mignard
  • 5,824
  • 6
  • 44
  • 60

2 Answers2

6

Better rotate objects using Snap.Matrix()

The way suggested by Ian, works for me perfectly while I used Chrome version < 36.0 When I updated Chrome to 36.0.1985.125 I saw bug with text rotation.

So, the soulution was using

var matrix = new Snap.Matrix();
matrix.rotate(-90, x, y);    
Paper.text(x, y, 'Text').attr({
                    fontWeight: 'bold',
                    fill: '#434343',
                    transform: matrix
                });

instead of

Paper.text(x, y, 'Text').attr({
                    fontWeight: 'bold',
                    fill: '#434343',
                    transform: 'r-90'
                });

Maybe it will be useful for somebody.

Community
  • 1
  • 1
Stafox
  • 1,007
  • 14
  • 25
5

Ideally you will control the rotation yourself, (rather than figuring it out from the attributes which is possible, but fiddlier). Animation can be easier, depending on what you need. Here is an example showing some basic animation with a rect (as circle rotation is just itself if around the centre)...

s = Snap(400, 620);

var myRect = s.rect(100, 100, 100, 200).attr({
    fill : 'white',
    stroke : 'black'
});
var myRotate = 45;

// if you wanted to rotate manually using your own adjust variable then this
// myRect.transform("r" + myRotate);
// but simpler in most cases to use the animate method


myRect.animate( { transform: "r" + myRotate + ",150,200" }, 1000 ); //rotate around centre of 150,200

Fiddle at http://jsfiddle.net/XG7ks/6/

Really it would probably be best to get a basic grounding on transformations with SVG (and translate, rotate, scale) just for it to make a bit more sense. You can 'see' the resultant transform with myRect.attr('transform') but I would probably leave that just at first.

Ian
  • 13,724
  • 4
  • 52
  • 75