简体   繁体   English

通过使用HTML5画布,如何创建具有时间间隔的无限循环

[英]By using HTML5 canvas, how to create infinite loop with time interval

I want to keep updating my image position with HTML5 canvas. 我想用HTML5画布不断更新我的图像位置。 I tried the following javascript code to do the work 我尝试了以下javascript代码来完成这项工作

window.onload = function start() {
  update();
}

function update() {
  document.getElementById('scoreband').innerHTML = score;
  var style = document.getElementById('bug').style;
  timmer = window.setInterval(function () {
    style.left = ((Math.random() * 100) + 1) + "%";
    style.top = ((Math.random() * 100) + 19) + "%";
  }, num);
}

But this is not working when it comes to HTML5 canvas. 但是当谈到HTML5画布时,这不起作用。 Is there similar way to do the same job in HTML5 canvas? 是否有类似的方法在HTML5画布中执行相同的工作?

To change any visual DOM content you should use requestAmimationFrame 要更改任何可视DOM内容,您应该使用requestAmimationFrame

Eg 例如

function update(time){
   // time is in ms and has a 1/1000000 second accuracy 
   // code that changes some content, like the canvas


   requestAnimationFrame(update);  // requests the next frame in 1/60th second
}

And to start it 并开始它

requestAnimationFrame(update);

As requested 按照要求

indow.onload = function start() {
  requestAnimationFrame(update);
}

function update() {
  document.getElementById('scoreband').innerHTML = score;
  var style = document.getElementById('bug').style;
  style.left = ((Math.random() * 100) + 1) + "%";
  style.top = ((Math.random() * 100) + 19) + "%";
  requestAnimationFrame(update);
}

Though it's not as good as requestAnimationFrame, setInterval's frame rate can be dynamic. 虽然它不如requestAnimationFrame好,但setInterval的帧速率可以是动态的。

//supposing num is defined lol
var timer = setInterval(update, num);
function update() {
  document.getElementById('scoreband').innerHTML = score;
  var style = document.getElementById('bug').style;
    style.left = ((Math.random() * 100) + 1) + "%";
    style.top = ((Math.random() * 100) + 19) + "%";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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