Canvas template

A canvas template for games and animations

by Amando Filipe

HTML

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

JavaScript

var canvas;
var ctx;
var WIDTH = document.getElementById('screen').width;
var HEIGHT = document.getElementById('screen').height;
var X = 0;
var R = 0;
var G = 0;
var B = 0;
var frameDelay = 10;
var speed = 5;


function move(){
    X += speed;
    if (X == WIDTH - 10) {
        speed *= -1;
    } else {
        speed *= 1;
    }

    if (X == 0) {
        speed *= -1;
    } else {
        speed *= 1;
    }    
}

function write() {
    ctx.beginPath();
    ctx.strokeStyle = 'orange';
    ctx.fillStyle = 'aqua';
    ctx.font = "bold 12px sans-serif";
    ctx.fillText("FPS = ", 10, 455);
}

function clear() {
    ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function timedVarChanges() {

}

function randomNum(min, max) {
    var X = Math.random() * max;
    while (X < min) {
        X = Math.random() * max;
    }
    return Math.round(X);
}

function rect(x, y, w, h) {
    ctx.beginPath();
    ctx.rect(x, y, w, h);
    ctx.fill();
}

function round(x, y, rad, shape, colour) {
    ctx.beginPath();
    ctx.fillStyle = colour;
    ctx.arc(x, y, rad, 0, Math.PI * 180, false);
    ctx.fill();
}

function init() {
    canvas = document.getElementById('screen');
    ctx = canvas.getContext('2d');
    draw();
    write();
    return setInterval(draw, frameDelay);
}

function draw() {
    clear();
    B += 2;
    R += 1;
    G += 0;
    ctx.fillStyle = 'rgb(' + R + ',' + G + ',' + B + ')';
    rect(X, 0, 10, 20);
    move();
}

init();