1 JS动画原理
1.1 物体匀速运动
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div></div>
<script>
var speedx=3;
var speedy=3;
var div=document.querySelector('div'); //querySelector():获取文档中选择器内的元素
function move(){
var currentleft=parseInt(window.getComputedStyle(div).left); //获取当前的left,因返回值是字符串,使用parseInt让返回值转化为整数类型
var left=currentleft+speedx;
div.style.left=left+'px'
// 斜方向匀速运动
// var currenttop=parseInt(window.getComputedStyle(div).top);
// var top=currenttop+speedy;
// div.style.top=top+'px'
}
//每隔20毫秒把自身位置加起来
setInterval(()=>{
move()
},20);
</script>
</body>
效果:
setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。setInterval(code, milliseconds); 或setInterval(function, milliseconds, param1, param2, …)。例如setInterval(function(){ alert(“Hello”); }, 3000);或setInterval(‘alert(“Hello”);’, 3000);
1.2 添加碰撞检测
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<style>
*{
margin: 0;
padding: 0;
}
/* 不显示滚动条 */
body{
overflow: hidden;
}
div{
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div></div>
<script>
var speedx=3;
var speedy=3;
var div=document.querySelector('div');
// 设置div块匀速运动
function move(){
var currentleft=parseInt(window.getComputedStyle(div).left);
var currenttop=parseInt(window.getComputedStyle(div).top);
check_border_collision(div);
var left=currentleft+speedx;
var top=currenttop+speedy;
div.style.left=left+'px';
div.style.top=top+'px'
}
// 添加碰撞检测
function check_border_collision(el) {
var style=window.getComputedStyle(div);
var left=parseInt(style.left);
var top=parseInt(style.top);
var w=parseInt(style.width);
var h=parseInt(style.height);
if(left<0){ //若检测到当前已经碰撞
left=0;
speedx*=-1; //运动方向设置为反方向
}
if(left>window.innerWidth-w){
left=window.innerWidth-w
speedx*=-1;
}
if(top<0){
top=0;
speedy*=-1;
}
if(top>window.innerHeight-h){
top=window.innerHeight-h
speedy*=-1;
}
el.style.left=left+'px';
el.style.top=top+'px';
}
//每隔20毫秒把自身位置加起来
setInterval(()=>{
move()
},20);
</script>
</body>
</html>