![](/img/trans.png)
[英]js -Uncaught TypeError: Cannot read property 'x' of undefined at object (ball
[英]Js object in a canvas game Uncaught TypeError: Cannot read property 'x' of undefined
我正在做一個畫布游戲,該游戲在畫布上繪制了一個對象。 但是它一直給我一個錯誤x是不確定的。 它以前曾經工作過,但是當我添加star功能時,它壞了。 任何幫助,我都很茫然。
var spaceShip = {
position: {
x: canvas.width / 2,
y: canvas.height - 20
},
size: {
width: 50,
height: 12
},
Velocity: {
x: 20
},
drawSpaceShip: function(){ // Draw Spaceship Object
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.fillRect(this.position.x, this.position.y, this.size.width, this.size.height);
ctx.fillRect(this.position.x + 15, this.position.y, this.size.width - 30, this.size.height / 2 - 12);
ctx.fillRect(this.position.x + 22.5, this.position.y, this.size.width - 45, this.size.height / 2 - 15);
ctx.closePath();
ctx.fill();
requestAnimationFrame(this.drawSpaceShip);
}// End drawShip function
};// End spaceShip Object
function Star(x, y, rad, velocity, fill){
this.x = Math.floor(Math.random() * 599);//this create a random number between 0 and 599 on the x axis
this.y = 0;
this.rad = Math.floor((Math.random() * 30) + 1);//this create a random number between 10 and 30 for the radius
this.velocity = 6;
this.fill = fill
this.draw = function(){
ctx.beginPath();
ctx.fillStyle = this.fill;
ctx.arc(this.x, this.y, this.rad, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
this.y += this.velocity;
}
}
function createMultipleStars(){
for (var i = 0; i <= 4; i++)
stars[i] = new Star(i * 50, 10, i, i, "rgba(255,215,0,0.6)");
}
createMultipleStars();
function step() {
ctx.clearRect(0,0,canvas.width, canvas.height);
for (var i = 0; i<= 4; i++)
stars[i].draw();
requestAnimationFrame(step);
}
spaceShip.drawSpaceShip();
step();
當分離this.drawSpaceShip
方法並將其傳遞給requestAnimationFrame
函數時,您將失去spaceShip
對象的上下文。 在這種情況下,使用全局對象上下文( this === window
)調用drawSpaceShip
。 您可以使用Function.prototype.bind方法顯式綁定上下文:
requestAnimationFrame(this.drawSpaceShip.bind(this));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.