js实现椭圆轨迹_用js实现一组图片同心椭圆周运动 图片有从小到大渐近效果
时间: 2024-01-20 07:04:29 浏览: 19
实现同心椭圆周运动可以使用正余弦函数来模拟物体的运动轨迹。同时,可以使用CSS中的transform属性来实现图片的大小渐变效果。下面是一个简单的实现代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>椭圆轨迹运动</title>
<style>
.container {
position: relative;
width: 400px;
height: 400px;
margin: 50px auto;
border: 1px solid #ccc;
border-radius: 50%;
overflow: hidden;
}
.box {
position: absolute;
width: 50px;
height: 50px;
background-color: #f00;
border-radius: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
<script>
var container = document.querySelector('.container');
var box = document.querySelector('.box');
var a = container.offsetWidth / 2;
var b = container.offsetHeight / 2;
var angle = 0;
var x, y;
function move() {
x = a * Math.cos(angle);
y = b * Math.sin(angle);
box.style.left = x + a + 'px';
box.style.top = y + b + 'px';
box.style.transform = 'translate(-50%, -50%) scale(' + (angle / (2 * Math.PI) + 0.5) + ')';
angle += 0.01;
requestAnimationFrame(move);
}
move();
</script>
</body>
</html>
```
在上面的代码中,container表示容器元素,box表示运动的物体元素。首先,通过获取容器元素的宽度和高度,计算出椭圆的两个半轴长度a和b。然后,使用Math.cos()和Math.sin()函数来计算物体在椭圆轨迹上的位置,并设置物体元素的left和top值,使其在容器中运动。同时,使用CSS的transform属性来实现物体大小的渐变效果,通过angle变量的变化来控制缩放比例,使物体在轨迹上运动的同时大小渐变。最后,使用requestAnimationFrame()函数来控制物体的刷新频率,使其看起来更加流畅。