static and dinamic canvas

by Marcus Carey

HTML

<div id="canvasesdiv">
    <canvas id="static" width=400 height=400>This text is displayed if your browser does not support HTML5 Canvas</canvas>
    <canvas id="dynamic" width=400 height=400>This text is displayed if your browser does not support HTML5 Canvas</canvas>
</div>

CSS

#canvasesdiv {
    position:relative;
    width:400px;
    height:400px;
}
#static {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
}
#dynamic {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
}

JavaScript

(function () {
    // static canvas
    var static = document.getElementById("static");
    var staticCtx = static.getContext("2d");
    
    // dynamic canvas
    var dynamic = document.getElementById("dynamic");
    var dynamicCtx = dynamic.getContext("2d");
    
    // animation status
    var FPS = 30;
    var INTERVAL = 1000 / FPS;

    // our background
    var myStaticObject = {
        x: 0,
        y: 0,
        width: static.width,
        height: static.height,
        draw: function () {
            staticCtx.fillStyle = "rgb(100, 100, 0)";
            staticCtx.fillRect(0, 0, static.width, static.height);
        }
    };

    // our bouncing rectangle
    var myDynamicObject = {
        x: 30,
        y: 30,
        width: 50,
        height: 50,
        gravity: 0.98,
        elasticity: 0.90,        
        velX: 10,
        velY: 0,
        bouncingY: false,
        bouncingX: false,
        draw: function () {   // example of dynamic animation code
            // clear the last draw of this object
           dynamicCtx.clearRect(this.x - 1, this.y - 1, this.width + 2, this.height + 2);            
            // compute gravity
            this.velY += this.gravity;
            // bounce Y
            if (!this.bouncingY && this.y >= dynamic.height - this.height) {
                this.bouncingY = true;
                this.y = dynamic.height - this.height;
                this.velY = -(this.velY * this.elasticity);
            } else {
                this.bouncingY = false;
            }
            // bounce X
            if (!this.bouncingX && (this.x >= dynamic.width - this.width) || this.x <= 0) {
                this.bouncingX = true;
                this.x = (this.x < 0 ? 0 : dynamic.width - this.width);
                this.velX = -(this.velX * this.elasticity);
            } else {
                this.bouncingX = false;
            }
            // compute new position
            this.x += this.velX;
            this.y += this.velY;...