canvas(小球碰撞)

使用 html5 中的 canvas, 实现小球相互碰撞并反弹,反弹算法比较简单.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bouncing balls</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Bouncing balls</h1>
    <canvas></canvas>

    <script src="main.js"></script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

style.css

html, body {
    margin: 0;
    padding: 0;
}

html {
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    height: 100%;
}

body {
    overflow: hidden;
    height: inherit;
}

h1 {
    font-size: 2rem;
    letter-spacing: -1px;
    position: absolute;
    margin: 0;
    top: -4px;
    right: 5px;
    color: transparent;
    text-shadow: 0 0 4px white;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

main.js

var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");

var WIDTH = document.documentElement.clientWidth;
var HEIGHT = document.documentElement.clientHeight;

canvas.width = WIDTH;
canvas.height = HEIGHT;

var config = {
    speedMin: -7,
    speedMax: 7,
    ballMin: 10,
    ballMax: 20,
    ballCount: 30
};

/**
 * function to generate random number
 *
 * @param max
 * @param min
 * @returns {*}
 */
function random (min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

/**
 * define Ball constructor
 *
 * @param x
 * @param y
 * @param velX
 * @param velY
 * @param color
 * @param size
 */
function Ball (x, y, velX, velY, color, size) {
    this.x = x;
    this.y = y;
    this.velX = velX;
    this.velY = velY;
    this.color = color;
    this.size = size;
}

/**
 * define Ball draw method
 */
Ball.prototype.draw = function () {
    ctx.beginPath();
    ctx.fillStyle = this.color;
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.fill();
};

/**
 * define Ball update method
 */
Ball.prototype.update = function () {
    if ((this.x + this.size) >= WIDTH) {
        this.velX = -this.velX;
    }
    if ((this.x - this.size) <= 0) {
        this.velX = -this.velX;
    }

    if ((this.y + this.size) >= HEIGHT) {
        this.velY = -this.velY;
    }
    if ((this.y - this.size) <= 0) {
        this.velY = -this.velY;
    }

    this.x += this.velX;
    this.y += this.velY;
};

/**
 * define Ball collision detection
 */
Ball.prototype.collisionDetect = function () {
    for (var j = 0; j < balls.length; j++) {
        var ball = balls[j];
        if (this !== ball) { // be care of this line, we can't compare one with itself
            var dxv = this.x + this.velX - (ball.x + ball.velX); //detect the next step which will updated
            var dyv = this.y + this.velY - (ball.y + ball.velY);
            var distance = Math.sqrt(dxv * dxv + dyv * dyv);

            if (distance <= this.size + ball.size) {
                ball.color = this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) +')';

                // rebound the balls when collision
                var dvx = this.velX - ball.velX;
                var dvy = this.velY - ball.velY;
                var dx = this.x - ball.x; // but when update just use this step
                var dy = this.y - ball.y;
                var xx_yy = dx * dx + dy * dy;
                var v_dvx = (dvx * dx * dx + dvy * dx * dy) / xx_yy;
                var v_dvy = (dvy * dy * dy + dvx * dx * dy) / xx_yy;
                this.velX = checkSpeed(this.velX - v_dvx);
                this.velY = checkSpeed(this.velY - v_dvy);
                ball.velX = checkSpeed(ball.velX + v_dvx);
                ball.velY = checkSpeed(ball.velY + v_dvy);
            }
        }
    }
};

/**
 * validate the speed
 *
 * @param speed
 * @returns {*}
 */
function checkSpeed (speed) {
    if (speed > config.speedMax) {
        speed = config.speedMax;
    } else if (speed < config.speedMin) {
        speed = config.speedMin;
    }
    return speed;
}

// define array to store balls
var balls = [];

/**
 * draw the balls loops
 */
function loop () {
    ctx.fillStyle = "rgba(0, 0, 0, 0.25)";
    ctx.fillRect(0, 0, WIDTH, HEIGHT);

    while (balls.length < config.ballCount) {
        var b_var = createBall();
        var ball = new Ball(
            b_var.x,
            b_var.y,
            random(config.speedMin, config.speedMax),
            random(config.speedMin, config.speedMax),
            "rgb(" + random(0, 255) + "," + random(0, 255) + "," + random(0, 255) + ")",
            b_var.r
        );
        balls.push(ball);
    }

    for (var i = 0; i < balls.length; i++) {
        balls[i].draw();
        balls[i].collisionDetect(); //detect before update
        balls[i].update();
    }

    // run again and again to realize the effect of the animation
    requestAnimationFrame(loop);
}

var createdBalls = [];

/**
 * ensure the created ball will not collision
 *
 * @returns {{x: *, y: *, r: *}}
 */
function createBall () {
    var x = random(0, WIDTH);
    var y = random(0, HEIGHT);
    var r = random(config.ballMin, config.ballMax);
    for (var i = 0; i < createdBalls.length; i++) {
        var dx = createdBalls[i].x - x;
        var dy = createdBalls[i].y - y;
        var distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < createdBalls[i].r + r) {
            return createBall();
        }
    }
    var ball = {
        x: x,
        y: y,
        r: r
    };
    createdBalls.push(ball);
    return ball;
}


loop();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190

效果图: 
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值