Reputation: 121
I want to keep updating my image position with HTML5 canvas. I tried the following javascript code to do the work
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. Is there similar way to do the same job in HTML5 canvas?
Upvotes: 1
Views: 936
Reputation: 11
Though it’s not as good as requestAnimationFrame, setInterval’s frame rate can be dynamic.
//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) + "%";
}
Upvotes: 1
Reputation: 54026
To change any visual DOM content you should use 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);
}
Upvotes: 2