Reputation: 19
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web Game </title>
</head>
<body onkeydown="keyDown(event)" onkeyup="keyUp(event)"></body>
<canvas id="gameCanvas1" width=600 height=400 style ="position:absoloute:top:0;left:0;background-image:url('img/background.jpg')">
Please upgrade your browser to support HTML5.<br/>
One recommendation is to install the latest Chrome or Firefox.
</canvas>
<script>
gamecanvas = document.getElementById("gamecanvas1");
ctx=gamecanvas.getContext("2d");
var img = new Image();
img.src = "img/left.png";
//MainLoop
MainLoop();
function MainLoop(){
grafx.drawImage(img,0,0)};
setTimeout(MainLoop, 1000/60); //about 60fps
}
</script>
</html>
I am trying to load the left.png image. I am making a basic platformer in HTML and JavaScript, but the image isn't being shown. I think the drawImage is being called before the image is loaded but I'm not sure how to fix it. Thanks.
Upvotes: 0
Views: 102
Reputation: 351
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web Game </title>
</head>
<body onkeydown="keyDown(event)" onkeyup="keyUp(event)"></body>
<canvas id="gameCanvas1" width=600 height=400 style ="position:absoloute:top:0;left:0;background-image:url('img/background.jpg')">
Please upgrade your browser to support HTML5.<br/>
One recommendation is to install the latest Chrome or Firefox.
</canvas>
<script>
console.log("i am here ");
var gamecanvas = document.getElementById('gameCanvas1');
var ctx=gamecanvas.getContext('2d');
var img = new Image();
img.src = "img/left.png";
//MainLoop
MainLoop();
function MainLoop(){
ctx.drawImage(img, 10, 10);
setTimeout(function(){
MainLoop();
}, 1000/60); //about 60fps
}
</script>
</html>
Upvotes: 0
Reputation: 3023
There are two problems I found.
P1:
grafx.drawImage(img,0,0)};
is wrong
it should be
ctx.drawImage(img,0,0);
P2: use image onload callback rather than setTimeout.
img.onload = function () {
ctx.drawImage(img,0,0);
};
Upvotes: 1
Reputation: 7490
You have several errors in your js code.
your element has an id
of gameCanvas1
, but you are trying to get an element with an id of gamecanvas1
(document.getElementById("gamecanvas1");
)
So the javascript wont find your canvas, which means the image wont be drawn. You also have an extra closing }
which is causing errors in your function
Try opening your browsers dev console, you'll see the issues
Upvotes: 0