我画面中的小球只有一个可以动,并且移动到画布的边缘时会直接移出,并未发生碰撞检测的效果
还是不行
canvas 的碰撞代码:
var balls = [];
window.onload = function() {
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
for(var i=0; i<200; i++){
var R = Math.floor(Math.random()*255);
var G = Math.floor(Math.random()*255);
var B = Math.floor(Math.random()*255);
var r = Math.random()*30 +20;
aBll = {
color: "rgb("+R+","+G+","+B+")",
r: r,
x: Math.random()*(canvas.width-2*r)+r,
y: Math.random()*(canvas.height-2*r)+r,
vx: (Math.random()*5+5)*Math.pow(-1,Math.floor(Math.random()*200)),
vy: (Math.random()*5+5)*Math.pow(-1,Math.floor(Math.random()*200))
}
balls[i] = aBll;
}
setInterval(
function(){
draw(ctx);
update(canvas.width,canvas.height);
},
50
);
}
function draw(context){
var canvas = context.canvas;
context.clearRect(0,0,canvas.width,canvas.height);
for(var i=0; i<balls.length; i++){
context.globalCompositeOperation = "xor";
context.fillStyle = balls[i].color;
context.beginPath();
context.arc(balls[i].x,balls[i].y,balls[i].r,0,2*Math.PI);
context.closePath();
context.fill();
}
}
function update(canvasWidth,canvasHeight){
for(var i=0; i<balls.length; i++){
balls[i].x += balls[i].vx;
balls[i].y += balls[i].vy;
if(balls[i].x - balls[i].r <= 0){
balls[i].vx = -balls[i].vx;
balls[i].x = balls[i].r;
}
if(balls[i].x + balls[i].r >= canvasWidth){
balls[i].vx = -balls[i].vx;
balls[i].x = canvasWidth - balls[i].r;
}
if(balls[i].y - balls[i].r <= 0){
balls[i].vy = -balls[i].vy;
balls[i].y = balls[i].r;
}
if(balls[i].y + balls[i].r >= canvasHeight){
balls[i].vy = -balls[i].vy;
balls[i].y = canvasHeight - balls[i].r;
}
}
}