onload事件不触发和图像没有被抽

问题描述 投票:0回答:1

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);
javascript onload drawimage
1个回答
1
投票

.call()链的功能是没有括号包装功能的语法错误。 load回调不应该叫,直到load处理器调度。你可以用名称来定义的功能和使用.bind()

function handleImgLoad() {
  // do stuff
}

img.onload = handleImgLoad.bind(this);
© www.soinside.com 2019 - 2024. All rights reserved.