onload事件是不是在“画()”方法烧制,而我的形象是没有得到在画布上绘制。我已经证实,路径是否正确,图像是存在的。
我无法找到问题的所在。预先感谢您的意见。
class Game {
constructor() {
this.gameWidth = 600;
this.gameHeight = 300;
this.gravity = 0.7;
this.canvasName = "gameBox";
this.canvas = document.getElementById(this.canvasName)
this.ctx = this.canvas.getContext('2d');
}
draw(image) {
let img = document.createElement('IMG');
this.ctx.fillStyle ='#F00';
this.ctx.fillRect(0, 0, this.gameWidth, this.gameHeight);
img.onload = function() {
this.ctx.drawImage(img, 0, 0, image.width, image.height, image.xPos, image.yPos, image.width, image.height);
}.call(this);
img.src = image.imageFile;
}
}
class Sprite {
constructor(width, height, imageFile, xPos, yPos) {
this.width = width;
this.height = height;
this.imageFile = imageFile;
this.xPos = xPos;
this.yPos = yPos;
this.xVel = 0;
this.yVel = 0;
}
}
let game = new Game()
let elephant = new Sprite(21, 13, "./images/elephant.png", game.gameWidth / 2, game.gameHeight - 13);
game.draw(elephant);
正确的版本:我已经重写它建议采取从guest271314,谢谢!似乎仍然我喜欢过于复杂,但它的作品。
class Game {
constructor() {
this.gameWidth = 600;
this.gameHeight = 300;
this.gravity = 0.7;
this.canvasName = "gameBox";
this.canvas = document.getElementById(this.canvasName)
this.ctx = this.canvas.getContext('2d');
}
drawSprite(image, img) {
this.ctx.drawImage(img, 0, 0, image.width, image.height, image.xPos, image.yPos, image.width, image.height);
}
draw(image) {
let img = document.createElement('IMG');
this.ctx.fillStyle ='#F00';
this.ctx.fillRect(0, 0, this.gameWidth, this.gameHeight);
img.onload = this.drawSprite.bind(this, image, img);
img.src = image.imageFile;
}
}
class Sprite {
constructor(width, height, imageFile, xPos, yPos) {
this.width = width;
this.height = height;
this.imageFile = imageFile;
this.xPos = xPos;
this.yPos = yPos;
this.xVel = 0;
this.yVel = 0;
}
}
let game = new Game()
let elephant = new Sprite(21, 13, "./images/elephant.png", game.gameWidth / 2, game.gameHeight - 13);
game.draw(elephant);
.call()
链的功能是没有括号包装功能的语法错误。 load
回调不应该叫,直到load
处理器调度。你可以用名称来定义的功能和使用.bind()
function handleImgLoad() {
// do stuff
}
img.onload = handleImgLoad.bind(this);