我正在尝试从 json 文件中获取数据来渲染 tilemap。但我一直收到这个错误Uncaught ReferenceError: renderTileMap is not defined
。
我试图将 renderTileMap 函数的主体放入 $.getJSON 函数中,并且它可以工作。地图在 0.2 毫秒内呈现,因此无需长时间等待。JSON 文件也是正确的。我不知道为什么 javascript 看不到这个方法。
getData() {
$.getJSON(this.file, renderTileMap);
}
renderTileMap(json) {
var actPosX = this.beginPosX;
var actPosY = this.beginPosY;
var activeTile = 0;
var tiles = json.tiles;
var tilesResources = json.tilesResources;
var lines = tiles.length / this.lineSize;
var i, y;
for(i = 1; i < lines; i++) {
for(y = 1; y < this.lineSize; y++) {
ctx.fillStyle = tilesResources[tiles[activeTile]];
ctx.fillRect(actPosX,actPosY, this.tileWidth, this.tileHeight);
actPosX += this.tileWidth;
activeTile++;
}
actPosY += this.tileHeight;
actPosX = this.beginPosX;
}
}
二者file
并renderTileMap
不是变量getData
的方法,它们是的上下文的一部分getData
(它是在对象)。您可以通过访问上下文,this
因此它必须是:
$.getJSON(this.file, this.renderTileMap);
现在虽然回调现在被调用,但它失去了它的上下文,所以你必须绑定它:
$.getJSON(this.file, this.renderTileMap.bind(this));
继续阅读:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句