Javascript requestAnimationFrame - 如何停止程序运行并等待绘制?

时间:2017-03-26 11:04:44

标签: javascript canvas requestanimationframe

我在javascript中编写了一个小程序,其中一个人基本上正在移动一个野外狩猎蘑菇,每次移动后(N,E,S,W)我想重绘整个画布,我也希望在我的画布上看到它HTML画布对象中的浏览器。我尝试使用requestAnimationFrame,但我只看到程序结束时的画布,而程序运行的浏览器是白色的,但我想每次人移动时刷新图片,我试着这样做:

function Guy(startPosition) {
    this.position = startPosition;
}
Guy.prototype.moveTo = function (direction) {
    if (direction == "N") this.position.x -= 1
    else if (direction == "S") this.position.x += 1
    else if (direction == "W") this.position.y -= 1
    else if (direction == "E") this.position.y += 1
    checkIfMushroom(this.position);
    requestAnimationFrame(drawField);
}

然后我有这个功能,玩家移动到蘑菇(改变它的x和y坐标):

function walktToMushroom(pos) {
    while (!player.position.equals(pos)) {
        var dx = player.position.x - pos.x;
        var dy = player.position.y - pos.y;
        while (dx != 0) {
            if (dx < 0) player.moveTo("S");
            else player.moveTo("N");
            dx = player.position.x - pos.x;
        }
        while (dy != 0) {
            if (dy < 0) player.moveTo("E");
            else player.moveTo("W");
            dy = player.position.y - pos.y;
        }
    }
}

drawField只需用ctx.stroke()重新绘制所有内容(蘑菇,玩家,字段)。

每次player(类型Guy)移动时,如何更新框架?

修改:drawField功能:

function drawField() {
    requestAnimationFrame(drawField);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawRaster();
    ctx.beginPath();
    ctx.strokeStyle = "#2FA0FF";
    ctx.lineWidth = 3;
    ctx.rect(player.position.x * rasterSize, player.position.y * rasterSize, rasterSize, rasterSize);
    ctx.stroke();
    ctx.closePath();
    mushrooms.forEach(function (mush) {
        ctx.beginPath();
        ctx.strokeStyle = "#A120FF";
        ctx.lineWidth = 3;
        ctx.rect(mush.x * rasterSize, mush.y * rasterSize, rasterSize, rasterSize);
        ctx.stroke();
        ctx.closePath();
    });
}
drawField();

0 个答案:

没有答案