绑定(this)和requestAnimationFrame

时间:2018-06-23 11:33:56

标签: javascript oop

在阅读了一些解决方案之后,我想到了:

class Car{
    constructor(carTag, throttle, yPosition){
        this.carTag = carTag
        this.carTag = new Image()
        this.throttle = throttle
        this.yPosition = yPosition
    }

    //Animate method that will animate cars across the screen
    animate(){
        const ref = this;
        requestAnimationFrame(function(){
            ref.animate();
        });
        const canvas = document.getElementById("gameboard");
        const ctx = canvas.getContext("2d");
        let xPosition = canvas.width;
        setTimeout (function(){
            ctx.clearRect(0, 0, xPosition, ref.yPosition);  
            ctx.drawImage(ref.carTag, xPosition, ref.yPosition);                    
            xPosition -= 4;
            console.log(xPosition);
       }, 1000/ref.throttle);
    }
}

const cars = new Car;
cars.carTag.src = "http://i.stack.imgur.com/Rk0DW.png";
cars.throttle = 2000;
cars.yPosition = 0;
cars.animate();

我仍然困扰的问题是为什么我的汽车图像停留在一个位置而不进行动画处理。为什么bind(this)会干扰requestAnimationFrame?

更新:此方法的最新版本不会产生错误消息。但是由于某种原因,xPosition并未更新,因此无法向左移动汽车图像。我尝试将requestAnimationFrame放在方法的底部,结果相同。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。谢谢大家!

  class Car{
    constructor(carTag, throttle, yPosition, xPosition, canvas, ctx){
        //carTag property
        this.carTag = carTag
        this.carTag = new Image()
        //throttle property
        this.throttle = throttle
        //yPosition property
        this.yPosition = yPosition
        //canvas, ctx property connecting with DOM
        this.canvas = canvas
        this.canvas = document.getElementById("gameboard");
        this.ctx = ctx;
        this.ctx = this.canvas.getContext("2d");
        //xPosition property
        this.xPosition = xPosition
       this.xPosition = this.canvas.width;
    }

    //Animate method that will animate cars across the screen
    animate(){
        const ref = this;
        setTimeout (function(){
            ref.canvas.width = ref.canvas.width;  
            ref.ctx.drawImage(ref.carTag, ref.xPosition, ref.yPosition);                    
            ref.xPosition -= 4;
            requestAnimationFrame(function(){
                ref.animate();
           });
       }, 1000/ref.throttle);
    }
}

const cars = new Car;
cars.carTag.src = "http://i.stack.imgur.com/Rk0DW.png";
cars.throttle = 2000;
cars.yPosition = 0;
cars.animate();