立即渲染图像

时间:2018-07-01 19:00:39

标签: javascript oop

我正在研究游戏。我需要一条道路可以立即加载到页面上,而不是在从一个屏幕构建到另一个屏幕的过程中有一个延迟。

//class pertaining to the background info
class Background{
    constructor(image, xPosition, yPosition, backgroundCanvas, ctx){
        //background image
        this.image = image;
        this.image = new Image();
        //xPosition
        this.xPosition = xPosition;
        //yPosition
        this.yPosition = yPosition;
        //backgroundCanvas and ctx
        this.backgroundCanvas = backgroundCanvas;
        this.backgroundCanvas = document.getElementById("background");
        this.ctx = ctx;
        this.ctx = this.backgroundCanvas.getContext("2d");

    }
    //displays background objects
    display(){
        const ref = this;
        ref.ctx.drawImage(ref.image, ref.xPosition, ref.yPosition, 25, 25);                    
        ref.xPosition -= 4;
        requestAnimationFrame(function(){
            ref.display();
        });
    }
}

//This will dynamically add both background and interactCanvas when page is loaded
(function init (){
    const board = document.getElementById("board");

    //creating background canvas
    const background = document.createElement("canvas");
    background.id = "background";
    background.width = 300;
    background.height = 150;

    //appending canvas to board
    board.appendChild(background);
    //drawing the road
    const tempArray = [20, 50, 80]; //road positions in tempArray
    for(let i = 0; i < tempArray.length; i++){
        roadDraw(tempArray[i]);
    }
    setInterval(function(){
        background.style.display = "block";
    }, 1300);
})();

//function draws roads
function roadDraw(position){
    const road = new Background;
    road.image.src = "pic/road.png";
    road.yPosition = position;
    road.xPosition = road.backgroundCanvas.width;
    road.display();
}

当页面加载时,我将setInterval放在会更改显示的javascript上。我遇到的问题是用户必须等待一秒钟左右才能显示道路。没有它,您会看到从右到左的道路。有没有办法让这种情况在加载时立即发生,而不是等待几秒钟左右才能显示出来。谢谢!

0 个答案:

没有答案