Reputation: 505
I'm trying to make a DOM object follow a circular path with jQuery.
So far, I'm trying to find the path by re-arranging a simple formula to determine a circle, so in pseudocode:
x = whatever. y = abs(sqrt(constant) -x)
This is what I have so far:
$(window).on('scroll', function()
{
//get intitial ratio
vRatio = (sky.dHeight - sky.height ) / (sky.height - 100)
hRatio = (sky.dHeight - sky.height ) / (sky.width - 100)
rawX = $(window).scrollTop() / hRatio;
x = rawX - sky.width/2;
y = Math.abs(Math.sqrt(sky.width/2) - x);
console.log(x)
console.log(y)
sun.ob.css({left : rawX, top: y})
})
Currently, it's following a triangular path rather than the gentle circular flow I was seeking with my eyes.
Just to give some context, this is on a parallax style document where the height is 000's of px tall (hence the ratios).
Upvotes: 3
Views: 601
Reputation: 96
Made this fiddle for you - uses some CSS rotation while scrolling down:
$(window).scroll(function () {
var scrollAmount = $(window).scrollTop();
var documentHeight = $(document).height() - $(window).height();
var scrollPercent = (scrollAmount / documentHeight);
var r = 180 * scrollPercent;
TweenMax.to($('#orbit'), 0.5, {
rotation: r
});
});
Should work on any window size.
Upvotes: 4
Reputation: 69242
Generally for (x,y)
pairs of a circle you need to use sin
and cos
, so something like
x = x0 + radius*Math.cos(angle)
y = y0 + radius*Math.sin(angle)
for a circle centered at (x0,y0)
, with a given radius
.
It looks like you might want to start with a value of x
and then determine y
? For that you could use:
angle = Math.acos( (x-x0)/radius )
y = y0 + radius*Math.sin(angle)
Upvotes: 2
Reputation: 46
If you're looking for a circular path then you probably want to use cos and sin ;)
I've made a quick example of a sun that is rotating within a div called "sky": jsfiddle example
var progression = 0;
update();
function update(){
var radiusX = 200;
var radiusY = 100;
var speed = 0.01;
var sky = $("#sky");
var sun = $("#sun");
var skyCenterX = sky.width() * 0.5 - sun.width() * 0.5;
var skyCenterY = sky.height() * 0.5 - sun.height() * 0.5;
progression = progression + speed;
var sunX = skyCenterX + radiusX * Math.cos(progression);
var sunY = skyCenterY + radiusY * Math.sin(progression);
$("#sun").css({left : sunX, top: sunY});
setTimeout(function(){update();}, 10);
}
I hope this is helpfull :D
Upvotes: 2