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);

}

最后的效果如下:

图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值