onload不触发,无法绘制图像

时间:2019-02-09 22:10:43

标签: javascript onload drawimage

onload没有在'draw()'方法中触发,并且我的图像没有在画布上绘制。我已经确认路径正确并且图像在那里。

我找不到问题所在。预先感谢您的建议。

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);

1 个答案:

答案 0 :(得分:1)

链接到函数的

load是一种语法错误,没有括号将函数包装。在load处理程序分派之前,不应调用.bind()回调。您可以使用名称定义函数并使用function handleImgLoad() { // do stuff } img.onload = handleImgLoad.bind(this);

{{1}}