javascript - HTML5 Canvas 和 JS 帧率慢慢降至 0

标签 javascript html canvas

我正在尝试为游戏设置 html 5 Canvas ,我的 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();

这是 fiddle :https://jsfiddle.net/gf7kt8k8/

最佳答案

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

context.beginPath();

draw()的开头。 这个问题之前被问过here

关于javascript - HTML5 Canvas 和 JS 帧率慢慢降至 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39948700/

相关文章:

javascript - 当我撤消迁移 sequelize 删除我的表或重命名为 table_backup

javascript - 使用 Javascript 我如何搜索字符串中的前三个字母并查看它们是否匹配 "ABC"?

javascript - Kineticjs 在按钮单击时 move 图像

javascript - 如何让多个重叠的 Canvas 一起全屏显示并保持重叠?

javascript - 如何使用javascript绘制带有动画的多个 Canvas 元素?

javascript - 将多个背景图像转换为 Array Javascript

javascript - 在 ASP.NET Web 应用程序中包含 Google Analytics javascript 代码

html - 响应式三 Angular 形 div

html - 如何用子元素覆盖设置 "border and overflow hidden"的元素的边框

python - Python 中的 HTML 文件解析