bind (this) и requestAnimationFrame - PullRequest
0 голосов
/ 23 июня 2018

После прочтения некоторых решений я придумал следующее:

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 голосов
/ 23 июня 2018

Я нашел решение.Спасибо всем!

  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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...