Created
June 20, 2022 15:04
-
-
Save jweinst1/c0cb5cf984fbdb9e9414587bfbba447d to your computer and use it in GitHub Desktop.
Sample JS canvas sprite game in html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Runner Game</title> | |
<style> | |
canvas { background: #eee; | |
display: block; | |
margin: 0 auto; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>My First Heading</h1> | |
<p>My first paragraph.</p> | |
<p id="coords">The coords go here</p> | |
<canvas id="myCanvas" width="512" height="512"></canvas> | |
<script type="text/javascript"> | |
var clickY = 0; | |
var clickX = 0; | |
document.getElementById("myCanvas").addEventListener("click", function (e){ | |
clickY = e.offsetY; | |
clickX = e.offsetX; | |
}); | |
var char = new Image(); | |
var charSpriteIndex = 0; | |
function init() { | |
char.src = 'canvas-char.png'; | |
window.requestAnimationFrame(draw); | |
} | |
var lastDrewChar = Date.now(); | |
function drawChar(ctx) { | |
document.getElementById("coords").innerHTML = "X is " + clickX.toString() + " Y is " + clickY.toString(); | |
var curTime = Date.now(); | |
if ((curTime - lastDrewChar) <= 100) | |
return; | |
switch (charSpriteIndex) { | |
case 0: | |
ctx.drawImage(char, charSpriteIndex, 0, 64, 64, clickX, clickY, 64, 64); | |
charSpriteIndex += 64; | |
break; | |
case 64: | |
ctx.drawImage(char, charSpriteIndex, 0, 64, 64, clickX, clickY, 64, 64); | |
charSpriteIndex += 64; | |
break; | |
case 128: | |
ctx.drawImage(char, charSpriteIndex, 0, 64, 64, clickX, clickY, 64, 64); | |
charSpriteIndex = 0; | |
break; | |
default: | |
console.log("Unknown issue with charSpriteIndex"); | |
} | |
lastDrewChar = curTime; | |
} | |
function draw() { | |
var ctx = document.getElementById('myCanvas').getContext('2d'); | |
ctx.clearRect(0, 0, 512, 512); // clear canvas | |
drawChar(ctx); | |
window.requestAnimationFrame(draw); | |
} | |
init(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment