所以基本上在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>
答案 0 :(得分:0)
不会及时加载resorces以使画布呈现它们。你可以通过这样的事情来实现这个目标(taken from article here):
<!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>
答案 1 :(得分:0)
在尝试将图像绘制到画布之前,可能尚未下载图像。要解决此问题,您可以使用图像的onLoad属性,这样绘图只会在图像加载后触发。
if (way === "hrz") {
this.image.onLoad = this.drawhrz();
}
...
if (way === "vrt") {
this.image.onLoad = this.drawvrt();
}