背景
我想实现多张图片绕一个中心点不断转动。
自己对JavaScript不是特别熟悉,但是仍然想实现这样的功能。网上找了许多,没有发现合适的样例。忽然想起大二时翻过的《JavaScript 王者归来》,上面有一段魔法代码,是多张图片进行8字运动。于是找到源码,作出更改,希望能实现多图圆周运动。
一张图片
先实现简单的情况,一张图片:
我们知道,椭圆的标准方程是x2a2+y2b2=1
换元,我们可以得到x=sinθ×ay=cosθ×b
接着将运动的中心移动到网页的中心:x1=x0+width2y1=y0+height2
确定转动的范围:x∼a=width/3y∼b=height/3
调整坐标一次移动的范围:角度变化的速度 —— speed
函数调用的时间间隔:setInterval()的时间参数
我是犬夜叉动漫迷,素材使用美美的桔梗:
(所有的图片都是在原图的基础上用PS缩小一半然后颜色设置128保存而成,否则图片过大)
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<img src="./quan3.jpg" width="50" height="50">
<script>0;
DI=document.images;
DIL=DI.length;
var width = document.body.scrollWidth;
var height = document.body.scrollHeight;
function A(){
DIS=DI[0].style;
DIS.position='absolute';
var speed = 0.005;
DIS.left = Math.sin(i*speed)*(width/3)+width/2;
DIS.top = Math.cos(i*speed)*(height/3)+height/2;
i++;
}
setInterval('A()',10); //5 for eyes, speed
void(0);
</script>
</body>
</html>
多张图片
接下来,进行多张图片的转动。
12张图片
多张图片的运动,涉及到点的空间差。总的角度差是2πspeed,分配到每一张图片则是2πspeed×DIL, DIL是图片的个数。然后调整自己满意的时间间隔即可。
放上亮亮的12星座图片。
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<img src="./picTMP/f1.png" width="60" height="60">
<img src="./picTMP/f2.png" width="60" height="60">
<img src="./picTMP/f3.png" width="60" height="60">
<img src="./picTMP/f4.png" width="60" height="60">
<img src="./picTMP/f5.png" width="60" height="60">
<img src="./picTMP/f6.png" width="60" height="60">
<img src="./picTMP/f7.png" width="60" height="60">
<img src="./picTMP/f8.png" width="60" height="60">
<img src="./picTMP/f9.png" width="60" height="60">
<img src="./picTMP/f10.png" width="60" height="60">
<img src="./picTMP/f11.png" width="60" height="60">
<img src="./picTMP/f12.png" width="60" height="60">
<script>0;
DI=document.images;
DIL=DI.length;
var width = document.body.scrollWidth;
var height = document.body.scrollHeight;
function A(){
for(var index=0;index<DIL;index++){
DIS=DI[index].style;
DIS.position='absolute';
var speed = 0.005;
var interV = 2*Math.PI/speed/DIL;
DIS.left = Math.sin(i*speed+index*interV*speed)*(width/3)+width/2; // the speed is change's range
DIS.top = Math.cos(i*speed+index*interV*speed)*(height/3)+height/2;
}
i++;
}
setInterval('A()',10); //set moving speed for eyes</script>
</body>
</html>