因此,基本上,在w3schools网站的Tryit编辑器中,我在此处编写的代码可以100%完美地工作。尽管我会提到第一次将其加载到编辑器中时,墙壁精灵不会显示为绘制,但是当我第二次单击运行时它确实会绘制。jsfiddle中发生了同样的事情。问题是,当我将代码复制到记事本并将其另存为html文件时,它将不再绘制墙了。我尝试了无数次更改图像来源,但是为什么它不起作用却没有任何意义。我已经在互联网上搜索了相同的问题以及stackoverflow,但是我只发现jsfiddle存在问题,有人忘记了它会自动添加乏味的方面并格式化所需的内容。
<canvas id="canvas"></canvas>
<script>
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.width = 32*16;
canvas.height = 32*10;
canvas.style.border = "1px solid black";
function component(source, x, y, way, amount) {
this.image = new Image();
this.image.src = source;
//horizontal drawing
this.drawhrz = function() {
for(i=0; i<amount; i++) {
context.drawImage(this.image, x, y, 32, 32);
x += 32;
}
}
if(way == "hrz"){
this.drawhrz();
}
//vertical drawing
this.drawvrt = function() {
for(i=0; i<amount; i++) {
context.drawImage(this.image, x, y, 32, 32);
y += 32;
}
}
if(way == "vrt"){
this.drawvrt();
}
};
window.onload = function() {
//initialize world components
var wallsrc = "http://i.imgur.com/QytfQJ1.png";
//draw the components
wall = new component(wallsrc, 0, 32*7, "hrz", 8);
};
</script>
未及时加载资源,以便画布渲染它们。您可以通过以下类似方法来完成此操作(摘自本文):
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas"></canvas>
<style>
</style>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload("http://i.imgur.com/QytfQJ1.png")
//--><!]]>
</script>
<script>
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.width = 32*16;
canvas.height = 32*10;
canvas.style.border = "1px solid black";
function component(source, x, y, way, amount) {
this.image = new Image();
this.image.src = source;
//horizontal drawing
this.drawhrz = function() {
for(i=0; i<amount; i++) {
context.drawImage(this.image, x, y, 32, 32);
x += 32;
}
}
if(way == "hrz"){
this.drawhrz();
}
//vertical drawing
this.drawvrt = function() {
for(i=0; i<amount; i++) {
context.drawImage(this.image, x, y, 32, 32);
y += 32;
}
}
if(way == "vrt"){
this.drawvrt();
}
};
window.onload = function() {
//initialize world components
var wallsrc = "http://i.imgur.com/QytfQJ1.png";
//draw the components
wall = new component(wallsrc, 0, 32*7, "hrz", 8);
};
</script>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句