Chr*_*ris 1 html javascript 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();
Run Code Online (Sandbox Code Playgroud)
这是小提琴: https: //jsfiddle.net/gf7kt8k8/
小智 5
原因是,你没有清理你的道路。使用
context.beginPath();
Run Code Online (Sandbox Code Playgroud)
开始时draw()。这个问题之前在这里被问过
| 归档时间: |
|
| 查看次数: |
923 次 |
| 最近记录: |