javascript - 我究竟做错了什么 ?我收到此错误:未捕获的 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>
解决方案
一个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;
});
}
推荐阅读
- python - 如何按月计算值的数量,然后在折线图中绘制图表?
- python - 如何重命名熊猫数据框列添加整数
- wordpress - 如果某些产品在购物车中,则将带有验证的自定义选择字段添加到 WooCommerce 结帐页面
- java - 如何在Java中创建几个整数和输入整数的“最佳拟合”比较?
- mysql - 根据日期选择最后插入的行
- java - Java如何从浏览器/系统自动请求用户PKI证书?
- google-cloud-platform - 如何禁用 gke 主机的自动升级(不仅仅是节点池)
- r - 在 R 中通过 ID 随机分配已建立的值
- ruby-on-rails - 没有路线匹配 [POST] "/webhooks/orders/fulfilled" Shopify rails
- c++ - 合并排序 C++ 错误排序