简体   繁体   中英

Pause and Resume for HTML5 canvas?

is there a way to pause / resume for HTML5 Canvas?

Say my code:

// Draw lines with decreasing widths
 for (i = 20; i > 0; i--)
 {
    var v=i*20
   ctx.strokeStyle = "rgb("+v+", "+v+", "+v+")";
   ctx.lineWidth = i;
   ctx.beginPath();
   ctx.moveTo(55, 20 + (20 - i) * 24);
   ctx.lineTo(335, 20 + (20 - i) * 24);
   ctx.stroke();
}

At the start of the code, I would like to Pause() meaning, i will tell the browser "ok you don't really have to waste any resources doing any actual drawing right now", i'm just gonna tell you the commands. Then after looping through i will call Resume() meaning "ok you can start drawing them now"

Btw does anyone know if there is a complete reference for the context object in javascript (I can't find it in google nor MDC..)

Try to draw the lines offscreen instead of "pausing" the canvas: http://kaioa.com/node/103

It will have the same result.

var renderToCanvas = function (width, height, renderFunction) {
  var buffer = document.createElement('canvas');
  buffer.width = width;
  buffer.height = height;
  renderFunction(buffer.getContext('2d'));
  return buffer;
};

(code fragment taken from above mentioned web page)

One way I have solved this issue of resource usage when nothing is happening is by setting a var isStarted = false;

Then turn it on and off based on whether or not things are animating.

Then use that var to control your setTimeout/requestAnimFrame

if (isStarted) {
  setTimeout(function() {}, 1000/33);// animation loop thing
}

I did this for a game environment I started to build and it works perfectly.

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