小球碰撞检测1.定义小球ball={x:100,y:100,r:5,speed:3,direction:Math.PI*2*Math.random()};2.绘制小球:更新函数用于更新小球,ctx.fillStyle='rgba(255,255,255,.05)';这句话是用来添加球的轨迹的。函数drawBall(ctx){更新();ctx.fillStyle='rgba(255,255,255,.05)';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='#000000';ctx.beginPath();ctx.arc(ball.x,ball.y,ball.r,0,Math.PI*2,true);ctx.closePath();ctx.fill()}3.updatefunctionfunctionupdate(){vardx=ball.x+Math.cos(ball.direction)*ball.speed;vardy=ball.y+Math.sin(ball.direction)*ball.speed;if(dx<0||dx>canvas.width||dy<0||dy>canvas.height){ball.direction=Math.PI*2*Math.random();更新();}else{ball.x=dx;球.y=dy;}}4。调用上面的函数functioncanvasApp(){varcanvas=document.getElementById("canvas");varcontext=canvas.getContext("2d");设置间隔(函数(){drawBall(上下文);},20);}最终效果如下:
