static and dinamic canvas with resize
improved version with resize event listener.
by Gustavo Carvalho
HTML
<div id="canvasesdiv">
<canvas id="static" width=400 height=400></canvas>
<canvas id="dynamic" width=400 height=400></canvas>
</div>
CSS
#canvasesdiv {
position: absolute;
left: 50%;
top: 50%;
}
#static {
position: absolute;
left: 0;
top: 0;
z-index: 1;
width: 100%;
height: 100%;
}
#dynamic {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 2;
}
JavaScript
(function () {
// container
var container = document.getElementById("canvasesdiv");
// 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;
}
//...