小球跳动的问题
怎么实现多个小球的跳动啊
怎么实现多个小球的跳动啊
2018-06-05
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> var RADIUS=4; var balls=[] window.onload=function() { var canvas = document.getElementById('canvas'); canvas.width = 1024; canvas.height = 500; var context = canvas.getContext("2d"); setInterval( function () { render(context); update(); } , 50 ); } function update(){ for( var i = 0 ; i < balls.length ; i ++ ){ balls[i].x += balls[i].vx; balls[i].y += balls[i].vy; balls[i].vy += balls[i].g; if( balls[i].y >= canvas.width-RADIUS ){ balls[i].y = canvas.height-RADIUS; balls[i].vy = - balls[i].vy*0.75; } } } function render(cxt){ cxt.clearRect(0,0,cxt.canvas.width,cxt.canvas.height) for( var i = 0 ; i < balls.length ; i ++ ){ cxt.fillStyle="#ff3"; cxt.beginPath(); cxt.arc( balls[i].x , balls[i].y , RADIUS , 0 , 2*Math.PI , true ); cxt.closePath(); cxt.fill(); } } </script> <canvas id="canvas" style="border:1px solid #aaa;display:block;margin:50px auto;"> <!--当前浏览器不支持Canvas,请更换浏览器后再试--> </canvas> </body> </html>
把每个小球当成一个对象放到数组里,遍历数组实现每个小球的动画。
//小球的基本运动 updataBalls : function(){ var _this = this; var balls = _this.data.balls; for(var i=0; i<balls.length; i++){ balls[i].x += balls[i].vx; balls[i].y += balls[i].vy; balls[i].vy += balls[i].g; if(balls[i].y >=_WINDOW_HEIGHT - _RADIUS){ balls[i].y = WINDOW_HEIGHT -RADIUS; balls[i].vy = -balls[i].vy*0.75; } } }
举报