Js object in a canvas game Uncaught TypeError: Cannot read property 'x' of undefined

Js object in a canvas game Uncaught TypeError: Cannot read property 'x' of undefined

我正在制作一个 canvas 游戏,它在 canvas 上绘制一个对象。但它一直给我一个错误 x is undefined。它以前是工作的,但是当我添加星号函数时它坏了。任何帮助,因为我不知所措。

  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 对象上下文。在这种情况下,drawSpaceShip 是使用全局对象上下文 (this === window) 调用的。您可以使用 Function.prototype.bind 方法显式绑定上下文:

requestAnimationFrame(this.drawSpaceShip.bind(this));