我究竟做错了什么 ?我收到此错误:Uncaught ReferenceError:未定义图像

时间:2018-08-13 04:10:49

标签: javascript

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

1 个答案:

答案 0 :(得分:1)

一个承诺有两个参数:解决和拒绝。

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