js balls

working with collision detection and creating arrays

by jay dowling

HTML

<!DOCTYPE html>
<html>
    
    <head>
        <title>Bubble Popper</title>
        </title>
        <link rel="stylesheet" type="text/css" href="bouncy_balls.css" />
    </head>
    
    <body>
        <canvas id="canvas" width="500" height="300"></canvas>
         <h1>Click it!</h1>

         <h1 id="numbers"></h1>

        <script type="text/javascript" src="bouncy_balls.js"></script>
    </body>

</html>

CSS

#canvas {
    background: black;
    display: block;
    margin: 15px auto;
}
h1 {
    text-align:center;
}

JavaScript

//get random number between 2 nums
function randNum(min, max) {
    return Math.random() * (max - min) + min;
}

// Get the canvas element
var canvas = document.getElementById("canvas");
// Get 2D context for drawing
var ctx = canvas.getContext("2d");
// create Particle Array
var balls = [];
//particle creation
function createBall(location) {
    balls.push({
        // location
        x: location.x,
        y: location.y,
        //velocity
        vx: randNum(-200, 200),
        vy: randNum(-200, 200),
        //acceleration
        ax: randNum(-150, 150),
        ay: randNum(-150, 150),
        radius: randNum(3, 50),
        color: '#' + Math.floor(Math.random() * 16777215).toString(16)
    });
}

//create 3 balls to start with in random spots
for (var i = 0; i < 3; i++) {
    var initLoc = {
        x: randNum(30, canvas.width - 30),
        y: randNum(30, canvas.height - 30)
    };
    createBall(initLoc);
}

//now make more balls with the mouse
//figure out mouse position
var rect = document.getElementById("canvas").getBoundingClientRect();
// Get canvas offset on page
var offset = {
    x: rect.left,
    y: rect.top
};
//create ball on click
window.onmousedown = function (e) {
    // IE fixer
    e = e || window.event;
    // get event location on page offset by canvas location
    var location = {
        x: e.pageX - offset.x,
        y: e.pageY - offset.y
    };

    createBall(location);
};

// draw all balls
function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (var i = 0; i < balls.length; i++) {
        var p = balls[i];
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI);
        ctx.fillStyle = p.color;
        ctx.fill();
    }
}
//update text info about balls
function updateInfo() {
    document.getElementById("numbers").innerHTML = "Number of balls:" + balls.length;
}
//edge collision method for balls on balls, the plus 5 keeps them from getting stuck mostly
function isColliding(a, b) {
   ...