https://github.com/kotone/ball.git 这是代码地址
http://htmlpreview.github.io/?https://github.com/kotone/bugRepository/blob/master/c-1.html 这是页面,50个小球的运动,简直就是混乱不堪。还请dalao帮忙看下问题在哪。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="canvas" style="border:1px solid #000; display: block;margin:50px auto"></canvas>
<script type="text/javascript">
var ctx;
var canvas;
const colors=["#F70A30","#F3118C","#AF14EF","#1915EA","#0FE7D3","#2BDE3D","#DEDC24","#E4991B"];
var ball=[];
window.onload=function(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.width=600;
canvas.height=600;
for (var i = 0; i <50; i++) {
var aBall={
r:Math.random()*20+10,
x:Math.random()*canvas.width,
y:Math.random()*canvas.height,
g:Math.random()*1.5,
vx:Math.pow(-1,Math.ceil(Math.random()*1000))*4,
vy:-5,
color:colors[Math.floor(Math.random()*colors.length)]
};
ball.push(aBall);
drawLoop();
};
}
function drawLoop(){
window.requestAnimFrame(drawLoop);
drawBall();
animetBall();
}
function drawBall(){
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
for (var i = 0; i < ball.length; i++) {
ctx.fillStyle=ball[i].color;
ctx.beginPath();
ctx.arc(ball[i].x,ball[i].y,ball[i].r,0,2*Math.PI);
ctx.closePath();
ctx.fill();
}
}
function animetBall(){
for (var i = 0; i < ball.length; i++) {
ball[i].x+=ball[i].vx;
ball[i].y+=ball[i].vy;
//ball[i].vy=ball[i].g;
//下
if(ball[i].y>=canvas.height-ball[i].r){
ball[i].y=canvas.height-ball[i].r;
ball[i].vy= -ball[i].vy;
}
//上
if(ball[i].y<=ball[i].r){
ball[i].y=ball[i].r;
ball[i].vy= -ball[i].vy;
}
//左
if(ball[i].x>=canvas.width-ball[i].r){
ball[i].x=canvas.width-ball[i].r;
ball[i].vx= -ball[i].vx;
}
//右
if(ball[i].x<=ball[i].r){
ball[i].x=ball[i].r;
ball[i].vx= -ball[i].vx;
}
}
}
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
</script>
</body>
</html>
HeyShinner