如何根据时间沿路径设置div

时间:2012-08-03 17:02:24

标签: jquery jquery-animate raphael ellipse angle

这个问题让我疯狂,我正在寻找洞察解决这个问题的最佳方法。

我有一个div $(“。sun”),我想沿椭圆的圆周移动,我用Raphael.js生成椭圆,这样椭圆就像屏幕一样宽,水平居中,并且高达宽度的一半,并且绝对位于0,0(左上角):

//draw ellipse that is as wide as the window and half as tall as the width
var paper = Raphael(document.getElementById("ellipse"), Wwidth, halfIt);
var c = paper.ellipse(Wwidth/2, halfIt/2, Wwidth/2, halfIt/2);
c.attr({'fill': 'transparent', 'stroke': 'red'});

jsfiddle here(在演示的jsfiddle中更改了值)

椭圆是天体在天空中行进的路径的程式化表示。这意味着在早上6点,太阳位于椭圆长轴处屏幕的最左侧。 12点太阳将位于屏幕的顶部中心,下午6点,太阳位于椭圆长轴的最右侧。

以度为单位,6AM = 180度,12中午= 90度,3PM = 45度,依此类推。基本上,每个小时在早上6点到下午6点之间相隔15度。添加计算分钟:

var hours = new Date().getHours();
(removed code that converts the numerical hour to my stylized degrees for brevity)
var mins = new Date().getMinutes();     
var minsdegree = mins * .25;    
var skyangle = hourdegree + minsdegree;

因此,例如,如果它是上午11:39,天角将等于114.75度。

挑战: 如何沿着椭圆的路径为太阳设置动画,使其与我的自定义角度相对应,具体取决于时间。从技术上讲,我不需要它“动画”,只需简单地对应于页面加载时的正确角度。但是,如果你让页面保持足够长的时间,那么沿路径设置动画会很简洁。

3 个答案:

答案 0 :(得分:2)

在这里:http://jsfiddle.net/y47Cr/54/

每秒更新一次。

答案 1 :(得分:1)

我会忽略你的小提琴,因为它不起作用。假设你有这些变量:

  • cxcy - 椭圆中心的坐标;
  • rxry - 椭圆的x和y半径;
  • skyangle - 要映射到椭圆的当前角度;
  • sun_widthsun_height - 太阳div的宽度和高度。
  • sun_margin - 您想要在太阳和椭圆之间允许的任何额外间隙的值(以像素为单位)(在0时,太阳将居中

您应该能够使用此javascript计算太阳的位置:

var sun_x = cx + Math.cos( Raphael.rad( skyangle ) ) * ( rx + sun_width + sun_margin );
var sun_y = cy + Math.sin( Raphael.rad( skyangle ) ) * ( ry + sun_height + sun_margin );

就这么简单。但是,我确实相信jeffery_the_wind在我进行教诲时将其钉在了一起。

答案 2 :(得分:0)

我想你会想要使用正弦函数来求解坐标。由于x轴较长,您可能希望通过某个乘数运行x坐标。

这是我提出的想法。从数学开始已经有一段时间了,所以我的一些术语可能是错的。

var x, y, top, left,
    originX = 100,
    originY = 50,
    axisLengthX = originX*2,
    axisLengthY = originY*2,
    dist = Math.sin(deg) * axisLengthX,
    sunEle = document.getElementById("sun");

x = dist;
y = dist * (axisLengthX / axisLengthY); // relationship between X and Y axis length of ellipse

top = originY - y;
left = originX - x;

sunEle.style = "top: " + top + "; left:" + left;