过去几周,我一直在尝试获取this代码以与我的引擎一起使用。
到目前为止,我已经加载了地图,并且所有数据都已存在,tileset已加载并分离为tile。
我的问题是,当我尝试在游戏循环中渲染地图时,出现类型错误
未捕获的TypeError:无法在'CanvasRenderingContext2D'上执行'drawImage':提供的值不是'(CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)类型的值
我不明白为什么我会收到此错误,因为我正在将每个图块绘制到画布元素并将其制成图像
这是我的代码
export class TiledMap{
constructor(){
this.tilesets = [];
this.tiles = [];
this.map = null;
}
load(jsonFile){
let self = this;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
self.parse(xhr.responseText);
}
}
xhr.open("GET",jsonFile,true);
xhr.send();
}
parse(json){
this.map = JSON.parse(json);
this.loadTilesetImages();
}
loadTilesetImages(){
let successCount = 0;
let errorCount = 0;
let self = this;
for(let ts=0; ts<this.map.tilesets.length; ts++){
let image = new Image();
image.addEventListener("load",function(){
successCount++;
if(successCount + errorCount == self.map.tilesets.length){
self.seperateTiles();
}
});
image.addEventListener("error",function(){
errorCount++;
alert("error loading: " + self.map.tilesets[ts].image);
});
image.src = this.map.tilesets[ts].image;
this.tilesets.push(image);
}
}
seperateTiles(){
let successCount = 0;
for(let ts=0; ts<this.tilesets.length; ts++){
let nTilesX = this.tilesets[ts].width / this.map.tilewidth;
let nTilesY = this.tilesets[ts].height / this.map.tileheight;
for(let ty=0; ty<nTilesY; ty++){
for(let tx=0; tx<nTilesX; tx++){
let tileCanvas = document.createElement("canvas");
let tileContext = tileCanvas.getContext("2d");
tileCanvas.width = this.map.tilewidth;
tileCanvas.height = this.map.tileheight;
let x = tx * this.map.tilewidth;
let y = ty * this.map.tileheight;
tileContext.drawImage(this.tilesets[ts],-x,-y);
let tile = new Image();
tile.src = tileCanvas.toDataURL("image/png");
this.tiles.push(tile);
}
}
}
}
drawTiles(){
for(let l=0; l < this.map.layers.length; l++){
let x=0;
let y=0;
if(this.map.layers[l].type === "tilelayer"){
for(let d=0; d < this.map.layers[l].data.length; d++){
if(d % this.map.width == 0 && d != 0){
y += this.map.tileheight;
x = 0;
}
if(this.map.layers[l].data[d] != 0){
engine["ctx"].drawImage(this.tiles[this.map.layers[l].data[d]],x,y);
}
x += this.map.tilewidth;
}
}
}
}
答案 0 :(得分:0)
使用console.log查看图块是什么时,它返回undefined,为解决此问题,我仅在知道图块集已完成加载并已拆分为图块后才渲染地图。完成之后,一切都按预期工作,并且还修复了seperateTiles()方法中的错误。