为了账号安全,请及时绑定邮箱和手机立即绑定

html5 制作 10个运动的小球?

html5 制作 10个运动的小球?

星空下的小孩 2016-11-22 11:15:36
是什么问题?addBall()若放在gameloop()中小球会出现,但小球数量不是10个,放在init()中,小球又不出现。 我实在很头大。 document.body.onload=game; var ball=[]; function init(){     addBall(); } function game(){     init();     lastTime=Date.now();     delTime=0;     gameLoop(); } function gameLoop(){     window.requestAnimationFrame(gameLoop);//循环调用     var now = Date.now();     delTime = now-lastTime;     lastTime=now;     if(delTime > 40){delTime = 40;}     drawBall(context2);     updateBall(canvasW,canvasH); } function addBall () {     for (var i = 0; i < 10; i++) {         var R = Math.floor(Math.random() * 255);         var G = Math.floor(Math.random() * 255);         var B = Math.floor(Math.random() * 255);         var radius = Math.random() * 10 + 20;         var aBall = {             x: Math.random() * (800 - 2 * radius) + radius * 2,             y: Math.random() * (600 - 2 * radius) + radius * 2,             r: radius,             color: 'rgb(' + R + ',' + G + ',' + B + ')',             vx: Math.pow(-1, Math.random() * 100) * (Math.random() * 1.5 + 0.5),             vy: Math.pow(-1, Math.random() * 100) * (Math.random() * 1.5 + 0.5)         };         ball.push(aBall);     } } function drawBall (cxt) {     cxt.clearRect(0,0,canvasW,canvasH);     for (var i = 0; i < ball.length; i++) {         cxt.fillStyle = ball[i].color;         cxt.globalAlpha = 0.6;         cxt.beginPath();         cxt.arc(ball[i].x,ball[i].y,ball[i].r,0,2*Math.PI);         cxt.closePath();         cxt.fill();     } } function updateBall (canW,canH) {     for(var i=0;i<ball.length;i++){         ball[i].x += ball[i].vx * delTime * 0.003;         ball[i].y += ball[i].vy * delTime * 0.003;         if(ball[i].x - ball[i].r <= 0 ){             //this.vx[i] = -this.vx[i];             ball[i].x = ball[i].r;         }         if(ball[i].x + ball[i].r >= canW ){             ball[i].vx = -ball[i].vx;             ball[i].x = canW - ball[i].r;         }         if(ball[i].y - ball[i].r <= 0 ){             //this.vy[i] = -this.vy[i];             ball[i].y = ball[i].r;         }         if(ball[i].y + ball[i].r >= canH ){             ball[i].vy = -ball[i].vy;             ball[i].y = canH - ball[i].r;         }     } }
查看完整描述

1 回答

?
星空下的小孩

TA贡献13条经验 获得超3个赞

已解决

查看完整回答
反对 回复 2016-11-23
  • 1 回答
  • 0 关注
  • 2082 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信