[英]HTML5 Canvas with Javascript , Image loading
<!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. 我正在尝试加载left.png图像。 I am making a basic platformer in HTML and JavaScript, but the image isn't being shown. 我正在用HTML和JavaScript制作基本的平台游戏,但没有显示图像。 I think the drawImage is being called before the image is loaded but I'm not sure how to fix it. 我认为在加载图像之前会调用drawImage,但是我不确定如何修复它。 Thanks. 谢谢。
There are two problems I found. 我发现了两个问题。
P1: P1:
grafx.drawImage(img,0,0)};
is wrong 是错的
it should be 它应该是
ctx.drawImage(img,0,0);
P2: use image onload callback rather than setTimeout. P2:使用图片加载回调而不是setTimeout。
img.onload = function () {
ctx.drawImage(img,0,0);
};
You have several errors in your js code. 您的js代码中有几个错误。
your element has an id
of gameCanvas1
, but you are trying to get an element with an id of gamecanvas1
( document.getElementById("gamecanvas1");
) 您的元素的id
为gameCanvas1
,但您正在尝试获取一个ID为gamecanvas1
的元素( document.getElementById("gamecanvas1");
)
So the javascript wont find your canvas, which means the image wont be drawn. 因此,javascript将找不到您的画布,这意味着将不会绘制图像。 You also have an extra closing }
which is causing errors in your function 您还需要额外关闭}
,这会导致函数错误
Try opening your browsers dev console, you'll see the issues 尝试打开浏览器开发者控制台,您将看到问题
<!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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.