[英]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>
我正在尝试加载left.png图像。 我正在用HTML和JavaScript制作基本的平台游戏,但没有显示图像。 我认为在加载图像之前会调用drawImage,但是我不确定如何修复它。 谢谢。
我发现了两个问题。
P1:
grafx.drawImage(img,0,0)};
是错的
它应该是
ctx.drawImage(img,0,0);
P2:使用图片加载回调而不是setTimeout。
img.onload = function () {
ctx.drawImage(img,0,0);
};
您的js代码中有几个错误。
您的元素的id
为gameCanvas1
,但您正在尝试获取一个ID为gamecanvas1
的元素( document.getElementById("gamecanvas1");
)
因此,javascript将找不到您的画布,这意味着将不会绘制图像。 您还需要额外关闭}
,这会导致函数错误
尝试打开浏览器开发者控制台,您将看到问题
<!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.