首页 > 解决方案 > 我究竟做错了什么 ?我收到此错误:未捕获的 ReferenceError:未定义图像

问题描述

我正在尝试使用 javascript 创建超级马里奥,但出现错误。我不明白为什么会出现此错误,请帮助我。在添加类和常量精灵之前,我没有收到此错误。我认为这与 const sprite 和类 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>

标签: javascript

解决方案


一个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;
  });
}

推荐阅读