Javascript 我不知道为什么我会得到一个“a”;“未定义”不是一个函数;错误
所以我不知道为什么,在第35行,我得到了这个错误,请有人解释为什么这是不工作的,因为我似乎不明白为什么 这是其上载网页的链接,您可以在控制台中看到错误消息以及所有代码 }) 在这里,您使用5个参数将Javascript 我不知道为什么我会得到一个“a”;“未定义”不是一个函数;错误,javascript,html,canvas,undefined,Javascript,Html,Canvas,Undefined,所以我不知道为什么,在第35行,我得到了这个错误,请有人解释为什么这是不工作的,因为我似乎不明白为什么 这是其上载网页的链接,您可以在控制台中看到错误消息以及所有代码 }) 在这里,您使用5个参数将地面初始化为障碍物。第五个,即c,是字符串“red”。因此,当您稍后调用ground.draw()时,您试图调用“red”.fillRect,而这不是字符串的有效成员函数 潜在的问题是障碍构造函数的参数c隐藏了全局c变量,因为它是一个更近的范围,因此隐藏了您打算使用的画布上下文引用。您介意在代码中指出
地面
初始化为障碍物
。第五个,即c
,是字符串“red”
。因此,当您稍后调用ground.draw()
时,您试图调用“red”.fillRect
,而这不是字符串的有效成员函数
潜在的问题是
障碍
构造函数的参数c
隐藏了全局c
变量,因为它是一个更近的范围,因此隐藏了您打算使用的画布上下文引用。您介意在代码中指出问题所在吗?复制情况:x=未定义;x()
。因此,找出(使用调试器并检查堆栈跟踪/完整错误消息)哪个表达式未定义,并且被错误地尝试作为函数调用。然后修复它,使它不是未定义的。
window.onload = function() {
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 600;
function Player() {
this.width = 20;
this.height = 20;
this.color = "red";
this.posY = (canvas.height / 2) - (this.height / 2);
this.posX = (canvas.width / 2) - (this.width / 2);
this.volY = 0;
this.volX = 0;
this.gravity = 0.5;
this.onGround = true;
this.draw = function() {this.posY += this.volY;
this.posX += this.volX;
this.volY += this.gravity;
c.fillStyle = this.color;
c.fillRect(this.posX, this.posY, this.width, this.height);
};
}
function Obstacle(x,y,w,h,c) {
this.posY = y;
this.posX = x;
this.width = w;
this.height = h;
this.color = c;
this.draw = function() {
c.fillStyle = this.color;
c.fillRect(this.posX, this.posY, this.width, this.height);
};
}
//objects
var player = new Player();
var ground = new Obstacle(0, canvas.height-20,canvas.width,20,"red");
//game update loop
window.setInterval(function() {
//clears screen
c.fillStyle = "lightblue";
c.fillRect(0,0, canvas.width, canvas.height);
//drawing objects
player.draw();
ground.draw();
}, 30);
var ground = new Obstacle(0, canvas.height-20,canvas.width,20,"red");