gpt4 book ai didi

javascript - onload 未触发并且图像无法绘制

转载 作者:行者123 更新时间:2023-12-03 00:13:42 29 4
gpt4 key购买 nike

onload 没有在“draw()”方法中触发,并且我的图像没有在 Canvas 上绘制。我已确认路径正确且图像存在。

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

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

关于javascript - onload 未触发并且图像无法绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54611281/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com