Reputation: 876
No errors, nothing. But the image still don't show up. When I console.log(background);
I see the src of the image in the console, like so <img src="ground.png">
. Here is the code:
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);
Upvotes: 0
Views: 83
Reputation: 1722
Try should call draw on image onload event something like below
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>
Upvotes: 3