HTML5 Canvas和JS帧率慢慢下降到0

HTML5 Canvas and JS Framerate slowly drops to 0

本文关键字:慢慢 帧率 Canvas JS HTML5      更新时间:2023-09-26

我正在尝试为游戏设置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/

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

context.beginPath();

draw()开头。这个问题之前有人问过