本来是打算尝试用canvas去制作这个动画,但是最后觉得,canvas能完成的动画通过简单的dom结构也能完成,就没必要耗费太多时间来做canvas,这动画是利用正弦定律加上随机概率,小狗有一定几率接到红色的运动球,正弦定律制作的是一个曲线轨迹,这样使动画看起来更具有运动轨迹曲线
先看下动画游戏效果,如果不能看到,请点击下面的运行代码
下面贴出代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script> <style> .box2{ width:400px; height:600px; margin:0 auto; border:1px solid #ccc; position: relative; } #ball{ background: red; width:30px; height: 30px; -moz-border-radius: 15px; /* Gecko browsers */ -webkit-border-radius: 15px; /* Webkit browsers */ border-radius:15px; position: absolute; top:550px; left:200px; } #dog{ left:100px; height: 220px; width: 220px; background:url("http://www.maotouying.org/zb_users/upload/2016/11/dog.jpg"); position: absolute; top:-30px; } </style> </head> <body> <div class="box2"> <div id="dog"></div> <div id="ball"></div> </div> <script> $(function(){ var a=0; var b=0.005; var c=1; var d=1; var e=Math.random()*(1-200)+200; $("#ball").click(function(){ var id = setInterval(function (){ a+=b; c+=d; if(a>180){ a=0 } if(c>=550){ c=0 a=0; clearInterval(id); location=location; } $("#ball").css({ top:(550-c), left:(200-Math.sin(a)*e) }); var f=188<(200-Math.sin(a)*e)&&(200-Math.sin(a)*e)<200; console.log(f); if(c==(550-97)){ if(188<(200-Math.sin(a)*e)&&(200-Math.sin(a)*e)<200){ alert('吃着了'); } } } ,5) }) }) </script> </body> </html>
前端开发QQ群:577185192