console
var playerX=0;
var playerY=0;
var playerY1=0;
var playSpeed=1000/60;
var jumpProcess;
var moveProcess;
var canvas = document.getElementById("player");
var ctx=canvas.getContext("2d");
var jumpHeight=360;
var nowHeight=0;
var jumpLength=180;
var isJumping = false;
var isWin=false;
function drawObstacle(position,height){
canvas1 = document.getElementById("background");
ctx1=canvas1.getContext("2d");
var height=80*height
var position=100*(position-1)
ctx1.fillStyle="#9b59b6";
ctx1.fillRect(position,500-height,100,height);
}
function createObstacles(){
drawObstacle(5,2)
drawObstacle(8,2)
}
function drawObj(nowHeight,upward){
ctx.fillStyle="#2196f3";
ctx.save();
if(upward){
ctx.translate(playerX, 460-nowHeight)
}
else{
ctx.translate(playerX, 100+nowHeight)
}
ctx.rotate(nowHeight * Math.PI/180)
ctx.fillRect(-40,-40,80,80);
ctx.restore();
playerX+=3;
}
function createSquare(){
drawObj(0,true)
}
function clearPlayer(){
ctx.clearRect(0,0,1200,500);
if(playerX>=canvas.width-80){
ctx.font = "40px Georgia";
ctx.fillStyle = "red";
ctx.fillText("YOU WIN !!!", 500, 150);
if(moveProcess!=null) clearInterval(moveProcess)
if(jumpProcess!=null) clearInterval(jumpProcess)
isWin=true;
isJumping = false;
}
else if(playerX>=320 && playerX<=420 && playerY<=200){
isWin=true;
if(moveProcess!=null) clearInterval(moveProcess)
if(jumpProcess!=null) clearInterval(jumpProcess)
reset()
isJumping = false;
}
else if(playerX>=620 && playerX<=720 && playerY<=160){
isWin=true;
if(moveProcess!=null) clearInterval(moveProcess)
if(jumpProcess!=null) clearInterval(jumpProcess)
reset()
isJumping = false;
}
}
function jump(){
if(!isJumping){
isJumping = true;
jumpProcess = setInterval(function(){jumpUp()},playSpeed)
}
}
function jumpUp(){
if(playerY<jumpHeight){
clearPlayer();
drawObj(playerY,true)
playerY+=6;
}
else{
clearInterval(jumpProcess)
jumpProcess = setInterval(function(){jumpDown()},playSpeed)
}
}
function jumpDown(){
if(playerY>0){
clearPlayer();
drawObj(playerY1,false)
playerY-=6;
playerY1+=6
}
else{
clearInterval(jumpProcess)
isJumping = false;
playerY1=0
moveProcess = setInterval(function(){move()},playSpeed)
}
}
function move(){
ctx.fillStyle="#2196f3";
clearPlayer()
ctx.fillRect(playerX,420,80,80);
playerX+=3;
}
function reset(){
playerY=0
playerX=0
playerY1=0
moveProcess = setInterval(function(){move()},playSpeed)
isWin=false;
}
function main(){
createSquare()
createObstacles()
moveProcess = setInterval(function(){move()},playSpeed)
addEventListener("keydown", function (e) {
if(!isWin){
clearInterval(moveProcess)
jump();
}
else{
}
}, false);
}
main();
<canvas id="player" width="1200" height="500" style="left:100px;position:absolute;border:1px solid #4caf50;z-index:421;"></canvas>
<canvas id="background" width="1200" height="500" style="left:100px;position:absolute;border:1px solid #4caf50;z-index:331;"></canvas>
body {TEXT-ALIGN: center;}
canvas {
margin-left: auto;
margin-right: auto;
}