How can one force the browser to redraw an image? - javascript

I'm working on a JavaScript game that involves throwing a snowball. I need the snowball to render as often as possible during its flight path. Chrome does all the calculations, including setting the style.left and style.top properties, but doesn't actually redraw the snowball until it reaches its destination. Opera doesn't have this problem.
A relevant point is that putting in an alert() after renderSnowball() fixes the problem, except using the alert() is an obvious issue.
Here's my code so far:
function throwSnowball()
{
var theta = parseFloat(angleField.value) * Math.PI/180 ;
var Vir = parseFloat(velocityField.value) ;
if (!isNaN(Vir) && !isNaN(theta) )
{
Vix = Math.cos(theta) * Vir * 50;
Viy = Math.sin(theta) * Vir * 50;
time = new Date() ;
var timeThrown = time.getTime() ;
while (snowballPosY > 0)
{
current = new Date() ;
var currentTime = current.getTime() ;
var timeElapsed = (currentTime - timeThrown)/5000 ;
snowballPosX += Vix * timeElapsed;
snowballPosY += Viy * timeElapsed;
Viy -= GRAVITY * timeElapsed ;
renderSnowball() ; //renderSnowball() sets the style.left
// and style.top properties to snowballPosX pixels
// and snowballPosY pixels respectively
timeThrown = currentTime ;
}
snowballPosX = 0 ;
snowballPosY = 50 ;
renderSnowball() ;
}
}

You're totally blocking the main thread. Have you tried using a setTimeout (even with a zero timeout) to allow other things to happen during your animation?
If you're willing to use experimental technology, requestAnimationFrame would be even better.
Edit: the setTimeout approach would look something like this (replacing the while loop):
var drawAndWait = function() {
if (snowballPosY > 0) {
// movement/drawing code here
setTimeout(drawAndWait, 20 /* milliseconds */);
} else {
// reset code that would normally go after your while loop
}
};
drawAndWait();
So each time the drawing finishes, it arranges for itself to be invoked again, if appropriate. Note that your throwSnowball function will return quickly; the throwing isn't actually done until later on. This takes awhile to get used to doing correctly; don't be too concerned if it's not intuitive at first.

Try getting out of the tight loop. Chrome may not want to redraw until your function exits. Try using setInterval or setTimeout to give Chrome a chance to repaint.

Related

Variable inside setInterval(function, var) is not changing / updating with increment

I am building a browser pet raising game. My plan is to use if/else to determine what the HP drop rate should be for the pet. If below a certain hunger / happiness, the HP will drop faster and faster.
I am using a variable setInterval, and the value inside is not update, but the value is updating when printing to the console.
let hp = 100;
let dropHPWeight = 6000;
let dropHPCall = setInterval(dropHP, dropHPWeight);
function dropHP() {
hp = (hp % 360) - 1;
console.log(dropHPWeight);
dropHPWeight = dropHPWeight + 6000;
}
Here I am dropping the HP every 6 seconds, and then as a test, I am seeing if it will increase, but it does not.
Where am I going wrong here?
As some are mentioning in the comments, you cannot change the interval of a setInterval once it has been initiated. You are better off using setTimeout. Like this:
let hp = 100;
let dropHPWait = 6000;
function dropHP() {
hp = (hp % 360) - 1;
dropHPWeight = dropHPWait + 6000;
if (somecondition){
setTimeout(dropHP, dropHPWait)
}
}
dropHP()
Now you call dropHP, which changes the interval, and then uses setTimeout to call itself again after the given increment. I stuck the setTimeout inside some conditional, because you don't want it to run forever (so you have to decide at what point you want it to stop running).

HTML Canvas animate sequence images is slow on IPAD

I have built a script which takes a sequence of images and displays them on a canvas element in a animation loop.
This works really well on my desktop, but on IPAD (3 retina) it is very slow. Could you suggest any way to improve the performance?
var videoItts = 0;
function playVideo() {
if(videoItts < 92) {
setTimeout(function() {
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.drawImage(imagesL[videoItts],0,0,1024,636);
requestAnimationFrame(playVideo);
videoItts ++;
}, 1000/22)
}
}
requestAnimationFrame(playVideo);
The imagesL is an array of pre-loaded images.
I would suggest not mixing setTimeout and requestAnimationFrame. You can solve it using only requestAnimationFrame:
var startTime = Date.now();
var fps = 22;
var lastDrawnIndex = null;
var totalFrames = 92;
function drawVideo() {
var currTime = Date.now();
var currFrameIndex = Math.round((currTime - startTime) / (1000/fps)) % totalFrames;
// Since requestAnimationFrame usually fires at 60 fps,
// we only need to draw the image if the frame to draw
// actually has changed from last call to requestAnimationFrame
if (currFrameIndex !== lastDrawnIndex) {
ctx.drawImage(imagesL[videoItts],0,0,1024,636);
lastDrawnIndex = currFrameIndex;
}
requestAnimationFrame(drawVideo);
}
requestAnimationFrame(drawVideo);
The idea is that for every call to requestAnimationFrame we calculate, based on the elapsed time and the desired animation frame rate, which frame index to draw. If it's different from last calculated frame index we draw it. Then we schedule drawVideo to be called next animation frame by calling requestAnimationFrame(drawVideo) at the end.
The code above will loop frames 0-91 continously at 22 fps. I removed the ctx.clearRect call, it is only needed if the frames contains transparency. So you might want to add that back.

Is Javascript multiplying these values wrong?

Allright, I know what machine precision is, but this, I can't understand...
Code:
console.log("meanX",meanX);
meanX2 = meanX * meanX; //squared
console.log("meanX2",meanX2);
Console output:
meanX 300.3
meanX2 28493.4400000000002
In case you are wondering, the correct value for meanX2 would be 90180.09
And this is only one of the many examples visible in the screenshot..
.toFixed(6) seems to fix this... But I have no idea why it doesn't work without it.
Edit
Ok, I don't want to post the whole program code here because in first place I'm not the only author, and second, I also wouldn't like this to be copied without our permission. But I'll gladly explain how I get this error and will post the whole method/function code here.
This code belongs, as you may have guessed from the window title, to a lane detection algorithm. We use Three.js/webgl to run some pre processing shaders on each frame of a video and then we analyze the resulting image. The method/function you see on the screenshot is a perpendicular line fitting algorithm and is part of the whole thing.
I can see the algorithm running nicely because I have the lane being drawn on top of the video, and It is well placed. Until suddenly the lane turns into an horizontal bar. This unexpected behavior happens exactly because of the phenomenon I described here, since it's from that moment that I start to see wrong math in the console.
Also, because the video and algorithm run at slightly different fps everytime, the problem doesn't always happen in the same moment of the video, and sometimes It doesn't happen at all.
Here is the code (it has some alterations because I was trying to isolate the issue):
this.perpendicularLineFit = function (points, slopeSign) {
var count = points.length;
var sumX = 0,
sumY = 0;
var sumX2 = 0,
sumY2 = 0,
sumXY = 0;
var meanX, meanY;
var i, lowp = {}, highp = {};
var B;
var slope;
var originY;
for (i = 0; i < count; i++) {
sumX += points[i].x;
sumY += points[i].y;
sumX2 += points[i].x * points[i].x;
sumY2 += points[i].y * points[i].y;
sumXY += points[i].y * points[i].x;
}
meanX = sumX / count;
meanY = sumY / count;
//If you uncoment this, problem reappears:
//var numeratorLeft = meanY * meanY;
console.log("meanX",meanX);
var meanX2 = meanX*meanX;
console.log("meanX2",meanX2);
var numerator = (sumY2 - count * (meanY * meanY)) - (sumX2 - count * meanX2);
var denominator = (count * meanX * meanY - sumXY);
B = 0.5 * (numerator / denominator);
slope = -B + slopeSign * Math.sqrt(B * B + 1);
originY = meanY - slope * meanX;
slope = isNaN(slope) ? slopeSign : slope;
originY = isNaN(originY) ? originY : originY;
lowp.y = this.lowY;
lowp.x = (this.lowY - originY) / slope;
highp.y = this.highY;
highp.x = (this.highY - originY) / slope;
return {
low: lowp,
high: highp
};
};
Now, I was trying to understand what was causing this, and the most bizarre thing is that it seems that when I place a statement of this form
var x = ... meanY * meanY ...;
before the meanX2 attribution, the issue happens. Otherwise it doesn't.
Also, I tried to catch this anomaly in the debugger but just when I enter the debugging tab, the problem disapears. And the values turn correct again.
I certainly don't believe in black magic, and I know that you are probably skeptic to this.
I would be too. But here is a link to a video showing it happening:
The video
Edit2:
I managed to reproduce this issue in another computer.. Both having ubuntu and using firefox (versions 20 and 21).
Edit3:
I'm sorry it took so much time! Here is a zip containing the issue. Just run it in any webserver. The code mentioned is in LaneDetection.js. Search for "HERE" in the file to find it.
https://docs.google.com/file/d/0B7y9wWiGlcYnYlo1S2pBelR1cHM/edit?usp=sharing
The problem might not happen in the first attempts. If that's the case refresh the page and try again. When the lines get horizontal you know it's there. As I said, I saw this problem happening in firefox versions 20 and 21 on ubuntu. In chrome it never happened.
By the way, I noticed that changing javascript.options.typeinference flag in firefox seems to stop the problem... I don't know exactly what that flag does, but maybe this optimization is not correctly implemented in firefox?
I can't say for sure that I actually have an answer but I think that I have confirmed that basilikum was correct to suggest a memory problem. Here's what I did: I took the first ten entries from your screenshot and calculated the correct answer. I then converted the correct answer and the wrong answer into the hexidecimal representation of the double-precision float. What I ended up with was the following:
292.416^2 = 85507.506 = 40F4E0381C71C71E
changed to 27583.373 = 40DAEFEB1C71C722
293.166^2 = 85946.694 = 40F4FBAB1C71C72A
changed to 27583.373 = 40DAEFEB1C71C722
295.818^2 = 87508.396 = 40F55D4658DC0876
changed to 28041.024 = 40DB62419637021F
294.500^2 = 86730.250 = 40F52CA400000000
changed to 27583.373 = 40DAEFEB1C71C722
297.000^2 = 88290.000 = 40F58E2000000000
changed to 28041.024 = 40DB62419637021F
221.750^2 = 49173.062 = 40E802A200000000
changed to 24964.000 = 40D8610000000000
300.300^2 = 90180.090 = 40F6044170A3D70A
changed to 28493.440 = 40DBD35C28F5C290
220.200^2 = 48488.040 = 40E7AD0147AE147B
changed to 25408.360 = 40D8D0170A3D70A4
300.600^2 = 90360.360 = 40F60F85C28F5C29
changed to 28493.440 = 40DBD35C28F5C290
213.000^2 = 45369.000 = 40E6272000000000
changed to 28032.326 = 40DB6014E5E0A72E
There's no persistent pattern to the change but there are a couple instances that are very telling of a memory issue. In the first two entries you can see that bytes 1, 2 and 3 were unchanged. In the 9th entry there's something even more odd. It would appear that bytes 0 - 3 were shifted left by exactly 4 bits! Upon considering the statement that the problem doesn't arise until after some time has passed and in light of these two anomalies, I'm fairly confident that you're encountering some sort of memory issue. Could it be, dare I say, a stack overflow?

Efficient ways to do a timer which updates every second in JavaScript

I had a task to make a progress bar and a process duration timer along with it. So, not thinking twice I did this:
<div class="mainInfo">
<div id="timer"><span id="elapsedText">0:00</span>/<span id="durationText">3:00</span></div>
<div id="progressBar"><div id="progress" style="width:0;"></div></div>
</div>​
And the JS:
var time = 1000;
var duration = 180;
var $progress = $("#progress");
var $elapsedText = $("#elapsedText");
updateTime();
function updateTime() {
var elapsed = time / 1000;
$elapsedText.text(Math.floor(elapsed / 60) + ":" + Math.floor(elapsed % 60));
$progress.css('width', (elapsed * 100 / duration) + "%");
time = time + 1000;
setTimeout("updateTime()", 1000);
}​
Time is actually retrieved from another variable - this ones for the demo (to illustrate that I actually have the value in miliseconds).
And it worked (not only on my PC), and still does, but the procmon shows a CPU spike on browser (chrome, ff) process when this cycle is running - 30-40% instead of regular 0,5%.
Is there a more efficient way to do this?
There is a standard function for that: SetInterval(function, delay_in_ms).
It calls a function in millisecond intervals.
Instead of
setTimeout("updateTime()", 1000);
use
setTimeout(updateTime, 1000);
The fact that you're invoking the compiler each second could really hurt performance. Passing a string to setTimeout is basically causing an eval within the setTimeout.
There is a default for that, and that is setInterval.
Be careful, the function passed as the first argument to setInterval is always executed in global scope.
Number two, a progress bar is usually created along-side expensive processes. You are using it for display purposes only and forcing a delay, which I don't particularly find useful, but if you like the layout, I guess you can go for it.
The way you would usually use it is:
executeFirstPotentiallyExpensiveProcess();// this is a call to a big function.
// then update the value of the progress bar in percentage style.
executeSecondPotentiallyExpensiveFunction()// this is the second part of your process.
// then again update..
// repeat until you have 100%.
// Basically, you logically divide the expenses of your various executions
// into numerable bits, preferably equal to one another for your convenience,
// but you chunk your loading process or whatever type of process and increment
// the progress after each chunk is complete.
Your use of jQuery disturbs me...
var time = 1000;
var duration = 180;
var $progress = document.getElementById("progress");
var $elapsedText = document.getElementById("elapsedText");
var beginTimestamp = new Date().getTime();
updateTime();
setInterval(updateTime,1000);
function updateTime() {
var now = new Date().getTime();
var elapsed = now-beginTimeStamp + time;
$elapsedText.firstChild.nodeValue = Math.floor(elapsed / 60) + ":" + Math.floor(elapsed % 60);
$progress.style.width = (elapsed * 100 / duration) + "%";
}​
Maybe without jQuery your browser might run better ;)
Try with the function setInterval.

Loops in HTML5 Canvas Animations

I am writing code for a HTML5 Canvas animation using Javascript. I am using requestAnimFrame for that. Animation is working fine for a point. But when i add a loop(for or while) in the function which is using requestAnimFrame or setTimeout, animation doesnt work. Its important for me to add the loop. ANy Suggestions to make that possible?
function animate(lastTime) {
var date = new Date();
var time = date.getTime();
var timeDiff = time - lastTime;
var linearSpeed = 100;
var linearDistEachFrame = linearSpeed * timeDiff / 1000;
var currentX = LINE.x;
var currentY = LINE.y;
var newY = currentY + linearDistEachFrame;
var newX = currentX + linearDistEachFrame;
context.beginPath();
context.moveTo(LINE.x, LINE.y);
lastTime = time;
var Xindex=LINE.arrayX.indexOf(newX);
//here am getting error..if i replace this with 'if' its working fine..and even if there is not a single LOC it doesnt work
while(Xindex!=-1) {
//processes the loop
}
context.lineTo(LINE.x, LINE.y);
context.fillStyle = "red";
context.fill();
context.lineWidth = LINE.borderWidth;
context.strokeStyle = "red";
context.stroke();
// request new frame
requestAnimFrame(function() {
animate(lastTime);
});
}
Try adding a break statement in the loop and see if that fixes it. If it does, it means that the condition has been met, and the code will be stuck in the loop forever unless you break out, or change Xindex to -1.
You need to narrow down exactly where the code is failing. One way to do this is by printing out debug statements at key parts of the code, so you know for sure they were executed, and what the value of important variables was.
You can use console.log("test"); for example, to write to Chrome's JavaScript console, or Firebug, or similar.
One trouble you'll face with debug output for a working animation program is the screeds of output. You might want to log only in certain interesting circumstances or you'll be drowning in a stream. Of data.

Categories