【发布时间】:2019-02-05 09:12:15
【问题描述】:
我正在为一个学校项目创建一个网站,并希望实现一个 javascript 游戏,但在遇到此错误之前我已经走了很长一段路。大多数错误我已经能够修复,但这个我无法修复。我的老师也不知道答案,所以我希望我能在这里找到一些帮助
这是我的代码
var player;
function startgame() {
gamearea.start();
playerupdater();
player = new component(30, 30, "blue", 10, 120);
}
var gamearea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateplayer, 50);
},
clear : function(){
console.log(this)
59------> this.canvas.clearRect(0, 0, this.canvas.width, this.canvas.height); <-
}
}
function playerupdatetimeout(){
setTimeout(playerupdater, 25)
}
function playerupdater(){
setInterval(gamearea.clear, 50);
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedx = 0;
this.speedy = 1;
this.x = x;
this.y = y;
this.update = function(){
ctx = gamearea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newpos = function(){
this.x += this.speedx;
this.y += this.speedy;
}
}
function updateplayer(){
player.update();
}
function movup(){
player.speedy -=1;
}
function movdown(){
player.speedy +=1;
}
function movright(){
player.speedx -=1;
}
function movleft(){
player.speedx +=1;
}
控制台指出第 59 行有错误(代码本身已指出)
如果您想自己查看错误,我的网站就在这里:https://jessep2000.github.io./home.html
我用于此页面的所有代码都在此存储库中
https://github.com/Jessep2000/Jessep2000.github.io/tree/master
希望有人知道答案,提前谢谢!
【问题讨论】:
-
setInterval(gamearea.clear, 50);改变了 clear 函数内部的this值,你可以修复这个写法setInterval(gamearea.clear.bind(gamearea), 50); -
谢谢!它使错误消失了,但现在控制台给出了这个错误:“Uncaught TypeError: this.canvas.clearRect is not a function at Object.clear (home.html:59)”
标签: javascript html canvas error-handling undefined