3、js动画

您所在的位置:网站首页 css3逐帧动画代码 3、js动画

3、js动画

2023-07-05 23:43| 来源: 网络整理| 查看: 265

js动画

js主要是靠定时器函数**setInterval(function,time)**来实现动画效果,他的作用是在每一个time时间都会执行一次function。

time是以毫秒为时间单位的

如何停止动画效果?

使用**clearInterval(名称)**来停止一个setInterval的执行。

let interval = setInterval(()=>{a++},1000); clearInterval(interval)

所以我们一般通过在定时器的函数中更改元素的style属性的值可以完成一个动画效果。

案例

使用js实现两个圆不停转动

效果图:js旋转圆圈.gif

实现思路:

最外面的圈为一个div,里面四个圈。确定圆心,半径等参数,通过圆的标准方程计算出圆的轨迹。通过定时器设置圆css绝对定位位置来让圆动起来。

代码

DOCTYPE html> js_circle *{ margin: 0px; padding: 0px; } #r1{ width: 300px; height: 300px; border: 1px solid red; border-radius: 50%; position: relative; } #r1>div{ position:absolute; } #r2{ width: 200px; height: 200px; border-radius: 50%; border: 1px solid gray; top: 50px; left: 50px; } #r3{ width: 100px; height: 100px; border-radius: 50%; border: 1px solid blue; top: 100px; left: 100px; } #circle_1{ width: 50px; height: 50px; border-radius: 50%; background-color: goldenrod; top: 130px; left: 0px; } #circle_2{ width: 50px; height: 50px; border-radius: 50%; background-color: green; top: 130px; left: 50px; } 开始第一个圆 开始第二个圆 //获取元素 let circle_1 = document.getElementById("circle_1"); let circle_2 = document.getElementById("circle_2"); function start_1() { let x=25,y=25; //定义半径以及圆心的位置 let r=125,x0=150,y0=150; //上半圆 let sbr = setInterval(()=>{ x++; y=-Math.sqrt(Math.pow(r,2)-Math.pow(x-x0,2))+y0; //设置坐标 circle_1.style.top = y-25+'px'; circle_1.style.left = x-25+'px'; if(x==275 && y==150){ clearInterval(sbr); //下半圆 let xbr = setInterval(()=>{ x--; y=Math.sqrt(Math.pow(r,2)-Math.pow(x-x0,2))+y0; //设置坐标 circle_1.style.top = y-25+'px'; circle_1.style.left = x-25+'px'; if(x==25 && y==150){ clearInterval(xbr); start_1(); } },16) } },16); } function start_2(){ let x=75,y=50; //定义半径以及圆心的位置 let r=75,x0=150,y0=150; let sbr = setInterval(()=>{ x++; y=-Math.sqrt(Math.pow(r,2)-Math.pow(x-x0,2))+y0; //设置坐标 circle_2.style.top = y-25+'px'; circle_2.style.left = x-25+'px'; if(x == 225 && y==150){ clearInterval(sbr); let xbr = setInterval(()=>{ x--; y=Math.sqrt(Math.pow(r,2)-Math.pow(x-x0,2))+y0; //设置坐标 circle_2.style.top = y-25+'px'; circle_2.style.left = x-25+'px'; if(x==75 && y==150){ clearInterval(xbr); start_2(); } },16) } },16) }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3