我有一个主要的 javascript 文件,它试图将 tilemap 绘制到游戏的 Canvas 上,并且我有一个包含的文件实际上绘制了 map 等,但是我在 firebug 中遇到了这个错误:
TypeError: Value could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement. [Break On This Error]
ctx.drawImage(mapTiles[map[x][y]],x*tilesize, y*tilesize);
调用我的 level.js 文件的主要 js 如下所示:
$(document).ready(function(){
var canvas = document.getElementById("TBG");
var context = canvas.getContext("2d");
var ui = new Gui();
var level = new Level();
//----------Login/Register Gui --------------
$('#TBG').hide();
$('#load-new').hide();
$('#reg').hide();
$('#login').hide();
//if login_but is clicked do ui.login function
$('#login_but').click(ui.login);
//if reg_but is clicked do ui.register function
$('#reg_but').click(ui.register);
$('#new_but').click(function(){
game_settings("new");
});
$('#load_but').click(function(){
game_settings("load");
});
//if login_sumbit button is clicked do ui.login_ajax function
$("#login_submit").click(ui.login_ajax);
$("#reg_submit").click(ui.register_ajax);
$("#welcome").on("click", "#logout_but", ui.logout);
//____________________________________________
//Initialisation of game
function game_settings(state){
if(state == "load"){
ui.load_game();
//do ajax call to load user last save
//level.level_init(0,1);
draw();
}
else{
//set beginning params
//Change screens
ui.new_game();
alert("new game");
}
}
function draw () {
context.clearRect(0,0,canvas.width,canvas.height);
level.draw(context);
setTimeout(draw, 30);
}
// End Loop
});
这行代码所在的文件 (level.js) 如下所示:
function Level(){
var tilesize = 32;
var map = 0;
var mapTiles = [];
// var saved_level = level;
//var saved_location = location;
map = [
[1,1,1,1,1,1,1,1,1,1],
[2,2,2,2,2,2,2,2,2,2]
];
for (x = 1; x <= 256; x++) {
var imageObj = new Image(); // new instance for each image
imageObj.src = "images/prototype/"+x+".jpg";
mapTiles.push(imageObj);
}
this.draw = function(ctx) {
for (var x = 0; x <= 31; x++){
for ( var y = 0; y <= 31; y++){
ctx.drawImage(mapTiles[map[x][y]],x*tilesize, y*tilesize);
}
}
};
}
你们有没有遇到过这个错误?
我该如何解决这个问题,谢谢 tom
最佳答案
忘掉 Canvas 和其他一切,看看 map
数组和使用它的代码。让我们撕掉 Canvas 代码并通过一些 console.log()
调用检查数组访问:
map = [
[1,1,1,1,1,1,1,1,1,1],
[2,2,2,2,2,2,2,2,2,2]
];
console.log( map.length );
console.log( map[0].length );
for (var x = 0; x <= 31; x++){
for ( var y = 0; y <= 31; y++){
console.log( x, y, map[x], map[x] && map[x][y] );
}
}
你看到问题了吗?您可以通过思考那些 console.log()
调用将打印的内容来发现它。如果没有,请将该代码粘贴到 Chrome 开发人员控制台中并查看它的作用。 (顺便说一句,最后一个参数有 map[x] && map[x][y]
,这在本质上与 map[x][y]
相同,但它保护当 map[x]
为 undefined
时代码崩溃,您将在日志中看到。)
现在我们现在 map[x][y]
有时是 undefined
,回到 drawImage()
调用,它使用它作为图像参数:
mapTiles[ map[x][y] ]
当 map[x][y]
为 undefined
时,该表达式的计算结果是什么?
关于javascript - 绘制到 Canvas 时出现控制台错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15645638/