javascriptsvgcss-transitionsraphael

SVG find orientation(angle) of a point to the x axis on a path


I am making parallax by moving an object on a path and it is working fine with getPointAtlength() but I also need to rotate this object with the path.

I need something like getPointAtLength() but for angles that I get the angle of the point. Rapheal seems to have a method to it but it isn't friendly to svg elements that is created in html or I don't know how to deal with it. Any ideas?

var l = document.getElementById('path');
var element=$('#svg_26')
$(window).scroll(function(){
    var pathOffset=parseInt($('#l1').css('stroke-dashoffset'));
    var p = l.getPointAtLength(-1*pathOffset);
    translation = 'translate('+p.x+'px,'+p.y+'px)'
    $(element).css('transform',translation);
})

Solution

  • getPointAtLength in Raphael returns an object with attribute 'alpha'. Alpha is the angle that you need along the curve. In the example above it would be p.alpha

    So you should be able to apply a rotation to the object rotated by p.alpha,

    Eg..

    myRaphElement.transform('t' + p.x + ',' + p.y + 'r' + p.alpha).

    The last part will rotate the element around its center.

    If you can't create the raph element itself as the svg is inline, I suspect you may be better off with a library like Snap.svg (which has mostly same commands as by same author), or you could possibly dynamically rotate by css transform using something like 'rotate('+l.alpha+','+l.x+','+l.y+')'

    Edit: I misread as it had Raphael in the tags, when its not being used.

    I personally would use Snap for this case, as Raphael doesn't add a lot here. You could possibly create a Raphael element off screen with the same path as the inline element just to use the angle, but feels like overkill to load a library for that.

    In Snap you could access the element with..

    myElement = Snap('#svg_26')
    p = myElement.getPointAtLength(-1*pathOffset);    
    myElement.transform('t' + p.x + ',' + p.y + 'r' + p.alpha)