JS小球绕着椭圆形的轨迹旋转并且近大远小

在ivx中案例如下:

VxEditor

效果如下,近大远小

JS小球绕着椭圆形的轨迹旋转并且近大远小_第1张图片

主要代码如下:

const centerX = 360 / 2; // 椭圆中心的X坐标
const centerY = 120 / 2; // 椭圆中心的Y坐标
const a = 100; // 长半轴
const b = 60; // 短半轴

const elementsWithClassName = document.querySelectorAll('.rotateball');
let angles = [0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2]; // 不同的起始角度

function animate() {
    elementsWithClassName.forEach((element, index) => {
        const angle = angles[index]; // 获取当前元素的角度
        const x = centerX + a * Math.cos(angle);
        const y = centerY + b * Math.sin(angle);
        element.style.left = x + 'px';
        element.style.top = y + 'px';

        const minHeight = 25;
        const maxHeight = 50;
        const normalizedY = (y - centerY + b) / (2 * b);
        const height = (maxHeight - minHeight) * normalizedY + minHeight;
        element.style.height = height + 'px';
        element.style.width = height + 'px';
        angles[index] += 0.01; // 控制角度增量,从而控制运动速度
    });

    requestAnimationFrame(animate);
}

animate();

// 添加滑动手势监听器
let initialX = null;

document.addEventListener('touchstart', (event) => {
    initialX = event.touches[0].clientX;
});

document.addEventListener('touchmove', (event) => {
    if (initialX === null) return;

    const currentX = event.touches[0].clientX;
    const deltaX = currentX - initialX;

    // 根据滑动方向来调整angles数组
    angles = angles.map(angle => angle + deltaX * 0.01);

    initialX = currentX;
});

document.addEventListener('touchend', () => {
    initialX = null;
});

 我还增加了滑动手势,可以左右滑动.

主要原理是提取classname,然后通过不停的改变style.left和style.top的值。来达到移动图片的目的。4个球的初始位置是不同的分别是

[0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2]

如果想实现更多的效果请联系我。我帮你研究研究

你可能感兴趣的:(javascript,开发语言,ecmascript,ivx,前端)