function moveCharacter() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
let position = Math.floor(gameFrame/staggerFrame) % spriteAnimation[playerState].loc.length
let frameX = spriteWidth * position
let frameY = spriteAnimation[playerState].loc[position].y
ctx.drawImage(playerImage, frameX, frameY, spriteWidth, spriteHeight, playerPositionX, playerPositionY, 150, 150)
gameFrame++
//playerImage.style.zIndex = "1"
requestAnimationFrame(moveCharacter)
}
moveCharacter()
In order to organize my canvas project, I have split it into three separate JavaScript files. The "bg.js" file handles the background element and should be positioned at the back of the canvas. On the other hand, the "enemies.js" file deals with the enemies and needs to be displayed in front of the page to avoid being hidden behind the background. Let me know if you require additional code snippets.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="Style.css">
<script src="script.js" defer></script>
<script src="bg.js" defer></script>
<script src="enemies.js" defer></script>
<title>Game</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
function animateBackground(){
ctx.clearRect(0, 0, canvas.width, canvas.height)
allLayers.forEach(object => {
object.update(),
object.draw()
})
requestAnimationFrame(animateBackground)
}
animateBackground()