Gas Bubbles

by John kuoppala

HTML

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

JavaScript

c = document.getElementById("canvas");
ctx = c.getContext("2d");

var fps = 60;
var lastUpdateTime = +new Date();
var spawnFreuenzy = 10;
var spawnTurn = 0;
var elapsedTime = 0;

var gasBubbles = new Array();

function gasBubble(x, size) {
    this.x = x;
    this.y = 0;
    this.velocity = 0.01;
    this.growthFactor = 0.005;
    this.size = size;
}

function gameloop() {
    var updateStartTime = +new Date();
    elapsedTime = updateStartTime - lastUpdateTime;
    update(elapsedTime);
    lastUpdateTime = updateStartTime;
    spawnTurn++;    
	if (spawnTurn >= spawnFreuenzy) {
		spawn();
		spawnTurn=0;
    }    
    
    setTimeout(gameloop,1000/fps);
}

function spawn() {
    gasBubbles[gasBubbles.length] = new gasBubble(Math.floor(Math.random()*c.width),Math.floor(Math.random()*10+5));   
}

function update(elapsedTime) {
    for (var i = 0; i < gasBubbles.length; i++) {
        gasBubbles[i].y += gasBubbles[i].velocity*elapsedTime;
        gasBubbles[i].size += gasBubbles[i].growthFactor*elapsedTime;
    }
}

function paint() {
    ctx.clearRect(0,0,c.width,c.height);
    for (var i = 0; i < gasBubbles.length; i++) {
        ctx.beginPath();
        ctx.arc(gasBubbles[i].x, gasBubbles[i].y, gasBubbles[i].size, 0, 2*Math.PI, false);
        ctx.closePath();
        ctx.fillStyle="green";
        ctx.fill();
    }
    
    ctx.fillText(elapsedTime,10,10);
    requestAnimationFrame(paint);
}
requestAnimationFrame(paint);
gameloop();