6

我有一个屏幕每 25 毫秒重绘一次,图像闪烁,这是我的代码

                var FRAME_RATE = 40;
                var intervalTime = 1000/FRAME_RATE;
                gameLoop();

                function gameLoop(){
                    context.clearRect(0, 0, 640, 640);
                    renderMap();
                    window.setTimeout(gameLoop, intervalTime);  
                }

这是 renderMap() 函数

function renderMap(){
                    var startX = playerX - (screenW / 2);
                    var startY = playerY - (screenH / 2);

                    maxX = playerX + (screenW / 2);
                    maxY = playerY + (screenH / 2);
                    $.getJSON('mapa3.json', function(json){
                        for (x = startX; x < maxX; x=x+32){ 
                            for (y = startY; y < maxY; y=y+32){
                                intTile = json.layers[0].data[((y/32)* 100) + (x/32)];
                                context.putImageData(getTile(intTile - 1), x - startX, y - startY);
                            }
                        } 
                    });

                    var imgCharacter = new Image();
                    imgCharacter.src = 'char.png';

                    var posX = (screenW - imgCharacter.width) / 2;
                    var posY = (screenH - imgCharacter.height) / 2;
                    imgCharacter.onload = function(){context.drawImage(imgCharacter, posX, posY)}       
                }

我需要对代码进行哪些更改才能停止闪烁?

4

2 回答 2

5

我相信这是因为您每次迭代都在加载图像。尝试将var imgCharacter...、以下行和图像的onload功能放在外面,renderMap这样它只运行一次

var imgCharacter = new Image();    
imgCharacter.onload = function () {
    renderMap();
}
imgCharacter.src = 'char.png';

function renderMap() {
    var startX = playerX - (screenW / 2);
    var startY = playerY - (screenH / 2);

    maxX = playerX + (screenW / 2);
    maxY = playerY + (screenH / 2);
    $.getJSON('mapa3.json', function (json) {
        for (x = startX; x < maxX; x = x + 32) {
            for (y = startY; y < maxY; y = y + 32) {
                intTile = json.layers[0].data[((y / 32) * 100) + (x / 32)];
                context.putImageData(getTile(intTile - 1), x - startX, y - startY);
            }
        }
    });

    var posX = (screenW - imgCharacter.width) / 2;
    var posY = (screenH - imgCharacter.height) / 2;

    context.drawImage(imgCharacter, posX, posY)
}

感谢markE让我知道这个onload功能也需要去外面renderMap,我第一次忽略了它

于 2013-08-24T23:00:20.993 回答
2

在绘制之前加载所有图像和其他数据并将它们存储在数组中。
更好地使用requestAnimationFrame
请记住,获取 JSON(或其他数据)可能需要一些时间。

于 2013-08-24T23:22:55.623 回答