Canvas学习之路(七)

小球的碰撞检测


1.定义小球

ball = {
    x: 100,
    y: 100,
    r: 5,
    speed: 3,
    direction: Math.PI * 2 * Math.random()
};

2.绘制小球:

update函数是更新小球用的,ctx.fillStyle = 'rgba(255, 255, 255, .05)';这一句是用来增添小球的运动轨迹的。

function drawBall(ctx) {
    update();
    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.update函数

function update() {
    var dx = ball.x + Math.cos(ball.direction)*ball.speed;
    var dy = 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();
        update();
    }else{
        ball.x = dx;
        ball.y = dy;
    }
}

4.调用上面的函数

function canvasApp() {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");


    setInterval(function () {
        drawBall(context);
    },
        20);

}

最后的效果如下:

Canvas学习之路(七)

相关推荐