Multiplane Parallax


There is nothing truly 3D in this example, but we can create the illusion using several 2D layers, and moving those layers at different speeds relative to one another.

The foreground layers move the fastest, creating the illusion that they are close by, with each layer back moving more slowly than the one before it, and the final background layer remaining completely stationary.


var ctx_middle;
var ctx_back;
var ctx_front;
var x = 0;
var y = 20;
var dy = 0;

window.onload = function(){

var ctx = $("#composite").children(".backdrop")[0].getContext("2d");
ctx.drawImage(drawBackdrop(),0,0);





var backtrees = new Image();
backtrees.src = "img/backtrees.png";
backtrees.onload = function(){
	ctx_middle = $("#composite").children(".backtrees")[0].getContext("2d");
	ctx_middle.drawImage(backtrees,0,0);
}

var waybacktrees = new Image();
waybacktrees.src = "img/waybacktrees.png";
waybacktrees.onload = function(){
	ctx_back = $("#composite").children(".waybacktrees")[0].getContext("2d");
	ctx_back.drawImage(waybacktrees,0,0);
}

var neartrees = new Image();
neartrees.src = "img/neartrees.png";
neartrees.onload = function(){
	ctx_front = $("#composite").children(".neartrees")[0].getContext("2d");
	ctx_front.drawImage(waybacktrees,0,0);
}


$(document).ready(function(){
	setInterval(function(){
		x+=5;
		y+= dy;
		if(y < 0){
			dy = 7;
		}
		dy-=0.2;
		
		ctx_middle.clearRect(0,0,600,400);
		ctx_middle.drawImage(backtrees,x%1250,y/2);
		ctx_middle.drawImage(backtrees,x%1250-1250,y/2);
		
		
		ctx_front.clearRect(0,0,600,400);
		ctx_front.drawImage(neartrees,x*2%2500,y);
		ctx_front.drawImage(neartrees,x*2%2500-2500,y);
		
		ctx_back.clearRect(0,0,600,400);
		ctx_back.fillStyle = "#006623";
		ctx_back.fillRect(0,y/4+75,600,400);
		ctx_back.drawImage(waybacktrees,x/2%1250,y/4);
		ctx_back.drawImage(waybacktrees,x/2%1250-1250,y/4);
		
	}, 20);
	
});



}

function drawBackdrop(){
var canvas = document.createElement("canvas");
canvas.width = 600;
canvas.height = 400;
var ctx = canvas.getContext("2d");
var grad = ctx.createLinearGradient(0,600,0,0);
grad.addColorStop(0,"#ffe97c");
grad.addColorStop(1,"#87a5ff");
ctx.fillStyle = grad;
ctx.fillRect(0,0,600,600);
ctx.fillStyle = "white";
for(var i = 0; i < 50; i++){
	ctx.globalAlpha = Math.random();
	ctx.fillRect(Math.random()*600,Math.random()*300,1,1);
}
ctx.globalAlpha = 1;



return canvas;
}


`