redrawing canvas html5 without flickering

前端 未结 2 883
心在旅途
心在旅途 2020-12-20 20:15

I\'ve a screen being redraw every 25ms, and images are flickering, here is my code

                var FRAME_RATE = 40;
                var intervalTime = 10         


        
相关标签:
2条回答
  • 2020-12-20 20:35

    Load all images and other data before draw and storage them inside array.
    Better use requestAnimationFrame.
    Remember, getting JSON (or other data) can take some time.

    0 讨论(0)
  • 2020-12-20 20:38

    I believe it is because you are loading the image each iteration. Try putting the var imgCharacter..., the following line, and the image's onload function outside of renderMap so it is only ran once

    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)
    }
    

    Thank you to markE for letting me know the onload function also needs to go outside renderMap, I overlooked it the first time

    0 讨论(0)
提交回复
热议问题