I recently created this HTML code and tested it, expecting an image to be displayed:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev Canvas Workshop</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var heroRadius = 20;
var heroX = 50;
var heroY = 50;
var upPressed = false;
var downPressed = false;
var leftPressed = false;
var rightPressed = false;
var heroSpeed = 2;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 87) {
upPressed = true;
}
else if(e.keyCode == 83) {
downPressed = true;
}
else if(e.keyCode == 65){
leftPressed = true;
}
else if(e.keyCode == 68){
rightPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 87) {
upPressed = false;
}
else if(e.keyCode == 83) {
downPressed = false;
}
else if(e.keyCode == 65) {
leftPressed = false;
}
else if(e.keyCode = 68) {
rightPressed = false;
}
}
function drawHero() {
var imageObj = new Image();
imageObj.onload = function() {
ctx.drawImage(imageObj, 69, 100);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawHero();
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
Unfortunately, the image is not appearing as intended. I was trying to create a game using an image for practice. The image shows up without requestAnimationFrame removed, but I require it for future movement implementation. Can anyone help me figure out why the image isn't displaying? Thank you!