Search code examples
javascriptanimationrotationraphael

A relative rotation in an animation


I have a problem with Raphael.js. I want to rotate the "compassScale" - set in the following code - in a relative manner.

This works for the paths, but all the texts "animate" to the absolute rotation of 30 degree. I want them to rotate to the 30 degrees relative from their actual positions.

var compassScale = paper.set();

var centerX = 200;
var centerY = 200;
var radius = 195;

var compasCircle = paper.circle(centerX, centerY, radius);

for(var i = 0; i < 360; i++) {
    var winkelRad = i * (Math.PI/180)
    var xStart = centerX + Math.sin(winkelRad) * radius;
    var yStart = centerY + Math.cos(winkelRad) * radius;
    var diff = 6;

    if(i % 10 === 0){
        compassScale.push(paper.text(centerX, centerY - radius + 18, i).rotate(i, centerX, centerY, true));
        diff = 12;
    } else if(i % 5 === 0) {
        diff = 8;
    }

    var xEnd = centerX + Math.sin(winkelRad) * (radius - diff);
    var yEnd = centerY + Math.cos(winkelRad) * (radius - diff);

    compassScale.push(paper.path("M" + xStart + " " + yStart + " L" + xEnd + " " + yEnd));
}

compassScale.animate({rotation:"30 " + centerX + " " + centerY}, 5000);

Solution

  • Like you said, the problem is that you're animating all elements to 30 degrees, not their current rotation + 30 degrees. It's actually quite simple once you think of it that way. Here is your revised code that works:

    var compassScale = paper.set();
    var texts = []; // array to hold the text elements
    
    var centerX = 200;
    var centerY = 200;
    var radius = 195;
    
    var compasCircle = paper.circle(centerX, centerY, radius);
    
    for(var i = 0; i < 360; i++) {
        var winkelRad = i * (Math.PI/180)
        var xStart = centerX + Math.sin(winkelRad) * radius;
        var yStart = centerY + Math.cos(winkelRad) * radius;
        var diff = 6;
    
        if(i % 10 === 0){
            texts.push(paper.text(centerX, centerY - radius + 18, i).rotate(i, centerX, centerY, true));
            diff = 12;
        } else if(i % 5 === 0) {
            diff = 8;
        }
    
        var xEnd = centerX + Math.sin(winkelRad) * (radius - diff);
        var yEnd = centerY + Math.cos(winkelRad) * (radius - diff);
    
        compassScale.push(paper.path("M" + xStart + " " + yStart + " L" + xEnd + " " + yEnd));
    }
    
    compassScale.animate({rotation:"30 " + centerX + " " + centerY}, 5000);
    // loop through the text elements, adjusting their rotation by adding 30 to their individual rotation
    for (var i = 0, l = texts.length; i < l; i += 1) {
        // node.attr("rotation") returns something like 50 200 200, so we have to split the string and grab the first number with shift
        texts[i].animate({rotation: (30 + +texts[i].attr("rotation").split(" ").shift()) + " " + centerX + " " + centerY}, 5000);
    }