HTML5 Canvas和JS Framerate慢慢降至0

时间:2016-10-09 21:24:47

标签: javascript html5 canvas

我正在尝试为游戏设置一个html 5画布,我的fps开始很好但随后它慢慢下降到0 fps并且滞后于浏览器窗口。我觉得我错过了一些非常重要的东西。

JS我用来管理刷新和绘图:

var stop = false;
var frameCount = 0;
var $results = $("#stats");
var fps, fpsInterval, startTime, now, then, elapsed;

var $canvas = $("#gameWorld")[0];
var context = $canvas.getContext("2d");

startAnimating(30);

function startAnimating(fps) {
    fpsInterval = 1000 / fps;
    then = Date.now();
    startTime = then;
    console.log(startTime);
    animate();
}

function animate() {

    // stop
    if (stop) {
        return;
    }

    // request another frame
    requestAnimationFrame(animate);

    // calc elapsed time since last loop
    now = Date.now();
    elapsed = now - then;

    // if enough time has elapsed, draw the next frame
    if (elapsed > fpsInterval) {
        then = now - (elapsed % fpsInterval);

        // draw stuff here
        draw();

        // Statistics
        var sinceStart = now - startTime;
        var currentFps = Math.round(1000 / (sinceStart / ++frameCount) * 100) / 100;
        $results.text("FPS: " + Math.round(currentFps));

    }
}

function draw() {
  context.clearRect(0, 0, width, height);

  drawBackground();
}

// Draw grid background
function drawBackground() {
  context.strokeStyle = '#e6ebf4';
  context.lineWidth = 1;

  var size = 50;
  for(var i=0; i < width + size; i+=size) {
    context.moveTo(i,0);
    context.lineTo(i,height);
    context.stroke();
  }
  for(var j=0; j < height + size; j+=size) {
     context.moveTo(0,j);
     context.lineTo(width,j);
     context.stroke();
  }
}

// resize the canvas to fill browser window dynamically
window.addEventListener('resize', resizeCanvas, false);

function resizeCanvas() {
  width = $canvas.width = window.innerWidth;
  height = $canvas.height = window.innerHeight;
}
resizeCanvas();

这是小提琴:https://jsfiddle.net/gf7kt8k8/

1 个答案:

答案 0 :(得分:1)

原因是,您没有清理路径。使用

context.beginPath();

draw()开头。 在here

之前询问了这个问题