没有错误,没有。但图像仍然没有出现。当我console.log(background);
时,我在控制台中看到了图像的src,就像<img src="ground.png">
一样。这是代码:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pirate</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="canvas" width="480" height="240"></canvas>
<script src="./script.js"></script>
</body>
</html>
JS:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var StyleSheet = function(image, width, height) {
this.image = image;
this.width = width;
this.height = height;
this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
context.drawImage(image, sx, sy, swidth, sheight, x, y, width, height);
}
}
var Loader = function(src) {
this.image = new Image();
this.image.src = src;
return this.image;
}
var background = new Loader("ground.png");
console.log(background);
var sprite = new StyleSheet(background, 50, 50);
sprite.draw(background, 0, 0, 16, 16, 0, 0, 50, 50);
答案 0 :(得分:3)
尝试在图像onload事件上调用draw,如下所示
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var StyleSheet = function(image, width, height) {
this.image = image;
this.width = width;
this.height = height;
this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
image.onload = function(){
context.drawImage(image, sx, sy, swidth, sheight, x, y, width, height);
}
}
}
var Loader = function(src) {
this.image = new Image();
this.image.src = src;
return this.image;
}
var background = new Loader("https://pbs.twimg.com/profile_images/902653914465550336/QE3287ZJ_400x400.jpg");
console.log(background);
var sprite = new StyleSheet(background, 50, 50);
sprite.draw(background, 0, 0, 16, 16, 0, 0, 50, 50);
<canvas id="canvas" width="480" height="240" style="border:1px solid #000000;"></canvas>