I'm making a simple canvas- game and I'm using requestAnimationFrame (Paul Irish's version) for the gameloop. I'm using a javascript countdown in the game (showing seconds and 100th of seconds), but it doesn't count down in the right speed. I know this has to do with the refresh- rate of the game, so that the counter updates every frame instead of every 100th second. How do I fix this?
Here's the timer object:
/**
* The timer as an object
*/
function Timer(position, time) {
this.position = position || new Vector(150,210);
this.time = time || 6000;
}
Timer.prototype = {
start: function() {
console.log('start running');
this.initial = this.time; //time in 100'ths of seconds
this.count = this.initial;
this.counter; //10 will run it every 100th of a second
clearInterval(this.counter);
//this.counter = setInterval(this.timer, 10);
this.timer();
},
timer: function() {
//console.log(this.count);
this.count--;
var res = this.count / 100;
//Show counter in canvas
return 'Tid kvar: ' + res.toPrecision(this.count.toString().length) + ' sekunder';
},
draw: function(ct) {
if(this.initial === undefined){this.start();} //Start the timer
ct.save();
if(this.count <=0){ //Remove timer if timer has reached 0
ct.clearRect(this.position.x, this.position.y, Racetrack.innerTrackWidth, Racetrack.innerTrackHeight);
return false;
} else { //draw timer
ct.save();
ct.font = 'bold 3em arial';
ct.fillStyle = 'orange';
ct.fillText(this.timer(), this.position.x, this.position.y);
}
ct.restore();
},
}
And the gameloop and the part calling the timer:
var init = function(canvas) {
timer = new Timer(new Vector(160,210), 3000);
}
var render = function() {
ct.clearRect(0,0,width,height);
ship.draw(ct);
racetrack.draw(ct);
//draw timer or results if timer reached 0
timer.draw(ct) !=false ? timer.draw(ct) : endFrame.draw(ct);
};
var gameLoop = function() {
var now = Date.now();
td = (now - (lastGameTick || now)) / 1000; // Timediff since last frame / gametick
lastGameTick = now;
if(timer.draw(ct) == false) { //stop the game if timer has reached 0.
cancelRequestAnimFrame(gameLoop);
console.log('Time\'s up!');
} else { //Otherwise, keep the game going.
requestAnimFrame(gameLoop);
}
update(td);
render();
};
I've also tried this as timer- object, but debugging this.count shows number the first loop, undefined the second loop and NaN every loop after that (And I'm not sure this will fix the timing issue either way?):
function Timer(position, time) {
this.position = position || new Vector(150,210);
this.time = time || 6000;
}
Timer.prototype = {
start: function() {
console.log('start running');
this.initial = this.time; //time in 100'ths of seconds
this.count = this.initial;
this.counter; //10 will run it every 100th of a second
clearInterval(this.counter);
this.counter = setInterval(this.timer, 10);
this.timer();
},
timer: function() {
console.log(this.count);
this.count--;
},
getTime: function() {
var res = this.count / 100;
return 'Tid kvar: ' + res.toPrecision(this.count.toString().length) + ' sekunder';
},
draw: function(ct) {
if(this.initial === undefined){this.start();} //Start the timer
ct.save();
if(this.count <=0){ //Remove timer if timer has reached 0
ct.clearRect(this.position.x, this.position.y, Racetrack.innerTrackWidth, Racetrack.innerTrackHeight);
return false;
} else { //draw timer
ct.save();
ct.font = 'bold 3em arial';
ct.fillStyle = 'orange';
ct.fillText(this.getTime(), this.position.x, this.position.y);
}
ct.restore();
},
}
Not sure if you are asking to display the time in 1/100 intervals or if the time is inaccurate when using setInterval.
A: setInterval should not be used for timing, as it is far from accurate and gets worse the smaller the interval, and even worse if you have animations running.
B: Browser's refresh at 1/60th of a second. You can force the display to render and present at 1/100 of a second but then depending on the graphics hardware it may never be displayed because the display is scanning pixels elsewhere on the screen at the time. Or you will get shearing when you overwrite the display just as the graphics is being written to the display.
Best way to get a countdown using requestAnimationFrame
var start = true; // flags that you want the countdown to start
var stopIn = 3000; // how long the timer should run
var stopTime = 0; // used to hold the stop time
var stop = false; // flag to indicate that stop time has been reached
var timeTillStop = 0; // holds the display time
// main update function
function update(timer){
if(start){ // do we need to start the timer
stopTime = timer + stopIn; // yes the set the stoptime
start = false; // clear the start flag
}else{ // waiting for stop
if(timer >= stopTime){ // has stop time been reached?
stop = true; // yes the flag to stop
}
}
timeTillStop = stopTime - timer; // for display of time till stop
// log() should be whatever you use to display the time.
log(Math.floor(timeTillStop / 10) ); // to display in 1/100th seconds
if(!stop){
requestAnimationFrame(update); // continue animation until stop
}
}
requestAnimationFrame(update); // start the animation
Forgot to add.
You are never going to get 100th of a second accuracy via that method. You will be on average 7-8 ms out. But unless you make it far more complex that is the best you can do. That 7-8ms average is constant and the same for 2 hours and 1 second and is just determined by the animation refresh time of about 16 odd ms.
Related
I want to animate stuff on a canvas using the window.requestanimationframe() method on top of two video (e.g. for highlighting important stuff in both videos). Currently, the animation runs and after that, the videos start playing together. So how can I execute everything (both videos and canvas animation) simultaneously?
class Animation {
constructor(canvas, data) {
this.canvas = document.getElementById(canvas);
this.ctx = this.canvas.getContext('2d');
this.data = data;
this.start = 0;
this.counter = 0;
this.running = false;
this.draw = function(){
console.log(this);
console.log("Draw");
if(!document.querySelector('video').playing){
// init
this.ctx.clearRect(0, 0, 300, 300); // clear canvas
// get data
var in_video_data = this.data['in_video'];
// draw CircleLineTimeSeries
for (var i=0; i<in_video_data.length; i++){
var item = in_video_data[i];
// if counter in phase intervall
if (this.counter >= item['start'] && this.counter <= item['end']){
console.log(item);
if (item['object'] == 'CircleLineTimeSeries'){
this.visualizeCircleLine(item['raw_kps'][0][this.counter],
item['raw_kps'][1][this.counter]);
}
}
}
// Increase time variable
this.counter += 1;
}
if (this.running){
window.requestAnimationFrame(this.draw.bind(this));
}
}
}
visualizeCircleLine(kps0, kps1){
this.ctx.beginPath();
this.ctx.moveTo(kps0[0], kps0[1]);
this.ctx.lineTo(kps1[0], kps1[1]);
this.ctx.stroke();
}
play(){
this.running = true;
window.requestAnimationFrame(this.draw.bind(this));
}
pause(){
this.running = false;
}
}
The code for running the video and the canvas animation:
/**
* Event handler for play button
*/
function playPause(){
if (running){
running = false;
animation.pause();
video0.pause();
video1.pause();
} else {
running = true;
animation.play();
video0.play();
video1.play();
}
}
Thank you in advance :)
As #Kaiido noted, you have to listen for updates in current time of the video. There is respective media event - timeupdate. Furthermore you should have a list of key frames of the video when to show your animation. Whenever timeupdate event fires, check the current time for reaching some key frame and, if so, notify your requestanimationframe callback to run animation via some shared variable.
Track the duration of continuous mouse movements on a webpage. A measurement begins when the cursor starts to move and ends when the cursor has stopped moving on the page. Reporting on duration happens thereafter. THis is what I have and works for while the mouse is moving and while it is stopped. However, I am confused how to track the start time and end time(i.e. the duration period of the mouse moving).
var myDiv = document.getElementById("myDiv");
var timeout;
//var startTime;
document.addEventListener("mousemove", function() {
myDiv.innerHTML = "You are moving";
if (timeout) clearTimeout(timeout);
timeout = setTimeout(mouseStop, 150);
});
function mouseStop() {
myDiv.innerHTML = "Stopped";
//console.log(Math.abs((startTime.getTime() - endTime.getTime())/1000));
}
You can count time on a different timer thread. Once you stop rest the timer.
var myDiv = document.getElementById("myDiv");
var timeout;
var timer = {stopped: true, time: 0};
setInterval(() => {
if (!timer.stopped) {
timer.time++;
}
}, 1000);
document.addEventListener("mousemove", function() {
timer.stopped = false;
myDiv.innerHTML = "You are moving";
if (timeout) clearTimeout(timeout);
timeout = setTimeout(mouseStop, 150);
});
function mouseStop() {
var totalTime = timer.time;
timer = {stopped: true, time: 0};
myDiv.innerHTML = 'Stopped! Total time: ' + totalTime + ' seconds';
}
<div id="myDiv"></div>
Hi i made a stopwatch in javascript and every time it updates, it deletes, and then after a second appears again and deletes. So every second it appears and disappears, making it blink. How can i make it appear until the next second updates, making a smooth transition.
Here is my code:
function GameTimer() {
var gameTimeMinutes = 0;
var gameTimeSeconds = 0;
var gameTime = "";
this.addTime = function() {
gameTimeSeconds += 1;
if (gameTimeSeconds < 10) {
gameTime = gameTimeMinutes + " : 0" + gameTimeSeconds;
} else {
gameTime = gameTimeMinutes + " : " + gameTimeSeconds;
}
if (gameTimeSeconds == 60) {
gameTimeSeconds = 0;
gameTimeMinutes++;
}
};
this.draw = function() {
graph.clearRect(0, 0, canvas.width, canvas.height);
var fontSize = 25;
graph.lineWidth = playerConfig.textBorderSize;
graph.fillStyle = playerConfig.textColor;
graph.strokeStyle = playerConfig.textBorder;
graph.miterLimit = 1;
graph.lineJoin = 'round';
graph.textAlign = 'right';
graph.textBaseline = 'middle';
graph.font = 'bold ' + fontSize + 'px sans-serif';
graph.strokeText(gameTime, 100, 30);
graph.fillText(gameTime, 100, 30);
};
this.update = function() {
this.addTime();
this.draw();
}.bind(this);
this.update();
}
var playerConfig = {textBorderSize: "1px", textColor: "black", textBorder: "solid"};
var canvas = document.getElementById("timer");
var graph = canvas.getContext("2d");
var gameTimer = new GameTimer();
setInterval(gameTimer.update, 1000);
<canvas id="timer" width="200" height="100"></canvas>
So just to clarify, i tried changing the interval time to ten seconds, and every ten seconds it appears and disappears, meaning that it is gone for the next ten seconds until it appears and disappears again. It doesn't stay there until the next update.
Thanks!
I believe that the flashing could be a result of setInterval not synchronizing with the screen's refresh rate. If so, requestAnimationFrame may be able to solve this.
This does use unnecessary system resources, but may solve your problem regardless.
Try this:
this.timeUntilUpdate = Date.now();
this.update = function(){
if(Date.now() - this.timeUntilUpdate > 1000){
this.addTime();
this.draw();
}
requestAnimationFrame(this.update);
}
And then at the end replace setInterval(gameTimer.update, 1000); with requestAnimationFrame(GameTimer.update) or possibly just GameTimer.update();
What is the difference between those two? requestAnimationFrame should be "intervaled" or invoked cca every 60milisecond on 60fps (depending on screen) and with setInterval you can set delay interval of invokation of function.
Yet i have made simple drawning animation with both , interval and requestAnimationFrame and it seems that interval function is smoother and work properly, while requestAnimation function broke browser (tested on mozilla/chrome and on 2 Pcs).
interval function:
function animate(x) {
var start = new Date();
var id = setInterval(function () {
var timepassed = new Date() - start;
var progress = timepassed / x.duration;
if (progress > 1) {
progress = 1;
}
var delta = x.delta(progress);
x.step(delta);
if (progress == 1) {
clearInterval(id);
}
}, x.delay);
}
requestAnimationFrame function:
function animate(x) {
var start = new Date();
var id = function () {
var timepassed = new Date() - start;
var progress = timepassed / x.duration;
if (progress > 1) {
progress = 1;
}
var delta = x.delta(progress);
x.step(delta);
requestAnimationFrame(id);
if (progress < 1) {
requestAnimationFrame(id);
}
}
requestAnimationFrame(id)
}
function to do drawning
function move(delta) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
animate({
delay:10,
duration: 4000,
delta: delta,
step: function (delta) {
ctx.clearRect(0, 0, c.width, c.height);
ctx.beginPath();
ctx.strokeStyle="red";
ctx.lineWidth = 15;
ctx.arc(150, 150, 70, 0*Math.PI, delta*(2 * Math.PI));
ctx.font="40px Georgia";
ctx.fillText((delta*100).toFixed(0)+"%",95,150);
ctx.stroke(); ;
}
});
}
move(function(p){return p});
demo for interval : http://jsfiddle.net/Trolstover/5tmu4j6z/
demo for requestAnimationFrame : http://jsfiddle.net/Trolstover/5tmu4j6z/1
just comment out
//requestAnimationFrame(id);
var timepassed = new Date() - start
see this: http://jsfiddle.net/5tmu4j6z/2/
After you call animate setInterval will run starting at the first interval, while requestAnimation will run before the next repaint of your canvas. The reason requestAnimation runs again is because it's recursive.
I am building a simple 2D game as an attempt to learn canvas. The character can run around a virtual environment, and a variable called yOffset controls his offset from the top of the screen. I also have a global variable called running which sets itself to true or false based on whether or not the character is running (not shown here). My goal is to make the character bob up and down whilst he is running, and all the below code does is spawn lots of setInterval()s. Is this the right way to make my character run, or should I do it another way? If so, how?
$(document).keydown(function(e) {
if(e.which == 97) {
running = true;
run();
} else if(e.which == 100) {
running = true;
run();
} else if(e.which == 119) {
running = true;
run();
} else if(e.which == 115) {
running = true;
run();
}
});
(yes, if the character stops running, the running variable does go to false [not shown here] - I've already made sure the running variable works well)
runTimer = 0;
function run() {
if(runTimer == 0 && running) {
runTimer = 1;
yOffset = 80;
setTimeout(function() {
yOffset = 120;
}, 150);
setTimeout(function() { if (running) { runTimer = 0;run(); } }, 300);
}
}
If you need more information, the version that I am currently working on is available here.
I think you can simplify your code, and in fact you must in the quite probable case where you'd like to add some other characters.
To allow re-use of the animation, it's better to separate what is an animation (== the different steps that your character will go through), and an animation state (== in which step your character is now).
I wrote here some elements of an animation system.
So i define what is an animation step, a whole Animation (which is so far only an array of animation step), and an Animator (which holds the state, one might see it as a 'reader' of an animation).
Once you defined the animation and animators, and started the animators, you just have to call tick(time) to have the animation move on, and offset() to read the offset, which is way simpler than fighting with a bunch of setIntervals.
http://jsfiddle.net/xWwFf/
// --------------------
function AnimationStep(duration, offset) {
this.duration = duration;
this.offset = offset;
// you might add : image index, rotation, ....
}
// --------------------
function Animation(animationSteps) {
this.steps = animationSteps; // Array of AnimationStep
}
// define a read-only length property
Object.defineProperty(Animation.prototype, 'length', {
get: function () {
return this.steps.length
}
});
// --------------------
function Animator() {
this.currentAnimation = null;
this.step = -1;
this.running = false;
this.remainingTime = 0; // remaining time in current step;
}
Animator.prototype.startAnim = function (newAnim, firstStep) {
this.currentAnimation = newAnim;
this.step = firstStep || 0;
this.remainingTime = newAnim.steps[this.step].duration;
this.running = true;
}
Animator.prototype.tick = function (dt) {
// do nothing if no animation ongoing.
if (!this.running) return;
this.remainingTime -= dt;
// 'eat' as many frames as required to have a >0 remaining time
while (this.remainingTime <= 0) {
this.step++;
if (this.step == this.currentAnimation.length) this.step = 0;
this.remainingTime += this.currentAnimation.steps[this.step].duration;
}
};
Animator.prototype.offset = function () {
return this.currentAnimation.steps[this.step].offset;
}
// ______________________________
// example
var bounceAnim = [];
bounceAnim.push(new AnimationStep(200, 10));
bounceAnim.push(new AnimationStep(180, 20));
bounceAnim.push(new AnimationStep(150, 30));
bounceAnim.push(new AnimationStep(300, 40));
bounceAnim.push(new AnimationStep(320, 45));
bounceAnim.push(new AnimationStep(200, 40));
bounceAnim.push(new AnimationStep(120, 30));
bounceAnim.push(new AnimationStep(100, 20));
var anim1 = new Animation(bounceAnim);
var animator1 = new Animator();
var animator2 = new Animator();
animator1.startAnim(anim1);
animator2.startAnim(anim1, 3);
// in action :
var ctx = document.getElementById('cv').getContext('2d');
function drawScene() {
ctx.fillStyle = 'hsl(200,60%, 65%)';
ctx.fillRect(0, 0, 600, 200);
ctx.fillStyle = 'hsl(90,60%,75%)';
ctx.fillRect(0, 200, 600, 200);
ctx.fillStyle = 'hsl(10,60%,75%)';
ctx.fillRect(200, 200 + animator1.offset(), 22, 22);
ctx.fillStyle = 'hsl(40,60%,75%)';
ctx.fillRect(400, 200 + animator2.offset(), 22, 22);
animator1.tick(20);
animator2.tick(20);
}
setInterval(drawScene, 20);