开发者

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 act开发者_开发技巧ual 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜