gpt4 book ai didi

javascript - 我究竟做错了什么 ?我收到此错误 : Uncaught ReferenceError: image is not defined

转载 作者:行者123 更新时间:2023-11-30 20:17:13 28 4
gpt4 key购买 nike

我正在尝试使用 javascript 创建 super 马里奥,但出现错误。我不明白为什么会出现此错误,请帮助我。在添加类和 const Sprite 之前,我没有收到此错误。我认为这与 const sprite 和 class SpriteSheet 有关。我附上了该错误的屏幕截图,我还输入了整个代码。

// A Function That loads image
function loadImage(url){ // give pram of url
return new Promise(resolve => { // create a promise
const image = new Image(); // set image to IMAGE() function
image.addEventListener('load', () => { // add eventlistener to load that image
resolve(image); // resolve image
});
image.src= url; // use param and src to enter url
});
}
// Class SpriteSheet

class SpriteSheet{
constructor(image, width, height){
this.image = image;
this.height = height;
this.width = width;
this.tiles = new Map();
}
// define a buffer so we don't have to create same element again and again.
define(name,x,y){
const buffer = document.createElement('canvas');
buffer.width = this.width;
buffer.heigth = this.height;
buffer.getContext('2d').drawImage(
this.image,
x * this.height,
y * this.width,
this.height,
this.width,
0,
0,
this.width,
this.height);
this.tiles.set(name,buffer);
}
draw(name, x, y){
const buffer = this.tiles.get(name);
context.drawImage(buffer,x,y);
};
}

// Draw a Canvas
const canvas = document.getElementById('screen');
const context = canvas.getContext('2d');

// create a Rectange
context.fillRect(0, 0, 500, 500);

// Define

const sprites = new SpriteSheet(image, 16, 16);
sprites.define('ground', 0,0);
sprites.draw('ground', context, 45,62);
// Load Image
loadImage('/img/tiles.png')
.then(image => {
context.drawImage(image,0,0,16,16,0,0,16,16); // (img,sx,sy,swidth,sheight,x,y,width,height) // First Four means subset you want to draw and other four means where you want to draw it
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Super Mario</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="\js\main.js" type="module"></script>
</head>
<body>
<canvas id="screen" width="640" height="640"></canvas>
</body>
</html>

最佳答案

一个 promise 有两个参数:resolve 和 reject。

function loadImage(url) {
return new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener('load', () => resolve(image));
image.addEventListener('error', () => reject(image));
image.src = url;
});
}

关于javascript - 我究竟做错了什么 ?我收到此错误 : Uncaught ReferenceError: image is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51815097/

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