Luc*_*eno -2 javascript html5 canvas undefined
所以我不知道为什么,在第35行,我得到这个错误,有人可以解释为什么这不起作用,因为我似乎无法弄清楚为什么?
这是其上传的网页的链接,您可以在控制台中看到错误消息,以及所有代码.http://matthew-hoyle.co.uk/files/beta/projects/platformer.php
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);
Run Code Online (Sandbox Code Playgroud)
};
var ground = new Obstacle(0, canvas.height-20,canvas.width,20,"red");
Run Code Online (Sandbox Code Playgroud)
在这里,您初始化ground为Obstacle5个参数.第五个c是字符串"red".所以,当你以后调用ground.draw()你试图调用时"red".fillRect,那不是字符串的有效成员函数.
根本的问题是,该参数c的的Obstacle构造函数隐藏全局c变量,因为它是一个更近的范围,因此躲在你打算使用画布上下文的引用.
| 归档时间: |
|
| 查看次数: |
206 次 |
| 最近记录: |