简体   繁体   中英

How to drop Frames in HTML5 Canvas

I am making a small game in HTML5 with the canvas elements. It runs great on MOST computers, but it is lags on others. However, it doesn't skip frames, it continues to render each frame and the game slows down. I am trying to write a function to skip frames, but I can't come up with a formula to do it.

I've tried searching around, but I have found nothing.

I have a function that renders the game called render and it is on a loop like this:

var renderTimer = setInterval("render(ctx)", 1000/CANVAS_FPS);

render()
{
/* render code here */
}

Thank you for any help, Brandon Pfeifer

This pattern will allow you to skip frames on computers known to be slow

var isSlowComputer=true;
var FrameSkipper=5;

function render(){

    // if this is a slow computer
    // just draw every 5th frame
    if(isSlowComputer && --FrameSkipper>0){ return; }

    // reset the frame skipper
    FrameSkipper=5;

    // draw your frame now

}

If your target market is people with HTML5 capable browsers, you can just use window.requestAnimationFrame. This allows all of your rendering logic to be bound in a simple place, and it will slow down only if it has to. It will try hard to reach the 16ms per frame allocation, which gets you to your 60fps.

var canvas = document.getElementById("#canvas"); (function drawFrame(){ window.requestAnimationFrame(drawFrame, canvas); // your main code would fire off here }()); As long as you let the browser figure out the frame rate you're golden.

I've written some different experiences using the canvas before, and until I used requestAnimationFrame things were a little choppy.

One other thing to keep in mind is the double buffer. If you are going to write a lot of things to the screen at any given moment, I find it is easier to write them all to a second hidden canvas element, then just use context.drawImg(buffer,0,0); that will get rid of a lot of the chop. As long as you have thought your code through the canvas shouldn't get choppy even under a lot of streign.

Good Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM