0
\$\begingroup\$

Can someone please explain whats going on in this code written by Paul Irish?

I did not understand the draw().

function draw() {

    var time = new Date().getTime() * 0.002;
    var x = Math.sin( time ) * 192 + 256;
    var y = Math.cos( time * 0.9 ) * 192 + 256;
    toggle = !toggle;

    context.fillStyle = toggle ? 'rgb(200,200,20)' :  'rgb(20,20,200)';
    context.beginPath();
    context.arc( x, y, 10, 0, Math.PI * 2, false );
    context.closePath();
    context.fill();

}
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

I will explain it line by line:

var time = new Date().getTime() * 0.002;

new Date().getTime() returns the current time in milliseconds (1 second = 1000 milliseconds). This is multiplied by 0.002 to scale the time -- slow it down, in this case.

var x = Math.sin( time ) * 192 + 256;

Scaling down the time is important, because it is used in this calculation as an angle. If it changes too fast, the angle will change too fast, too (wrapping around at 2pi, i.e. every ~6ms in real time, or every ~3s in scaled time). Therefore, the individual circles would be drawn far away from each other if the time would not have been scaled.

Math.sin(time) returns the sine for the given angle, i.e. a value in range [-1;1], changing continuously over time. This value is multiplied by 192, so that the result is in range [-192;192]. Adding 256 yields [64;448]. Therefore, the x coordinate for this circle will change infinitely over time from 64 to 448 to 64..., following the sine curve.

var y = Math.cos( time * 0.9 ) * 192 + 256;

Here, the time is scaled some more, so that the circles are vertically closer together. Except that, the computation is analog to that from above, but this time the cosine curve is used, which only changes the starting value of the y coordinate relative to the starting value of the x coordinate (you will get a very similar result using sine here, too).

toggle = !toggle;

This toggles a boolean every time the function is called.

context.fillStyle = toggle ? 'rgb(200,200,20)' :  'rgb(20,20,200)';

The drawing color is determined by checking that boolean. Therefore, blue and yellow circles are drawn in succession.

context.beginPath();
context.arc( x, y, 10, 0, Math.PI * 2, false );
context.closePath();
context.fill();

Finally, this is the drawing code, using all the computed values.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.