Physics

by yinyann

HTML

<canvas id="canvas" width="500" height="300"></canvas>

CSS

#canvas {
    background: black;
    display: block;
    margin: 15px auto;
}

JavaScript

// Get the canvas element
var canvas = document.getElementById( "canvas" );
// Get our 2D context for drawing
var ctx = canvas.getContext( "2d" );

// Frames-per-second
var FPS = 30;

// Particle Array
var particles = [];
for ( var i = 0; i < 10; i++ ) {
    particles.push({
        // Create random values for each of these:
        x: randNum( 30, canvas.width - 30 ),
        y: randNum( 30, canvas.height - 30 ),
        vx: randNum( -200, 200 ),
        vy: randNum( -200, 200 ),
        ax: randNum( -150, 150 ),
        ay: randNum( -150, 150 ),
        radius: 30,
        color: "rgba(255, 255, 255, .5)"
    });
}

// Game loop draw function
function draw() {
    ctx.clearRect( 0, 0, canvas.width, canvas.height );

    for ( var i = 0; i < particles.length; i++ ) {
        var p = particles[i];
        ctx.beginPath();
        ctx.arc( p.x, p.y, p.radius, 0, 2 * Math.PI );
        ctx.fillStyle = p.color;
        ctx.fill();
    }
}

function randNum(min, max){
    var nb = Math.floor(Math.random() * (max - min)) + min;
    return nb;
}

// Game loop update function
function update() {
    for ( var i = 0; i < particles.length; i++ ) {
        var p = particles[i];

        // Update code here:
        p.vx += p.ax / FPS;
        p.vy += p.ay / FPS;
        p.x += p.vx / FPS;
        p.y += p.vy / FPS;

        if ( ( p.x - p.radius ) < 0 ) {
            p.x = p.radius;
            p.vx = -p.vx;
        }
        if ( ( p.x + p.radius ) > canvas.width ) {
            p.x = canvas.width -p.radius;
            p.vx = -p.vx;
        }
        if ( ( p.y - p.radius ) < 0 ) {
            p.y = p.radius;
            p.vy = -p.vy;
        }
        if ( ( p.y + p.radius ) > canvas.height ) {
            p.y = canvas.height - p.radius;
            p.vy = -p.vy;
        }
    }
}

function tick() {
    draw();
    update();
}

setInterval( tick, 1000 / FPS );