0

I hope this isn't too abstract of a question, but I've been trying to figure this out

when programming generative/interactive animations ( in many languages ) it's common to see the following structure:

global variables
a setup function 
a draw function ( the loop ) 

for example this canvas sketch in javascript

var ctx, w, h,
    x = y = 1,
    xd = yd = 1;

function setup() {
    var canvas = document.getElementById("canvas");
    canvas.width = w = window.innerWidth;
    canvas.height = h = window.innerHeight;
    ctx = canvas.getContext("2d");
}

function draw() {
    ctx.clearRect(0, 0, w, h);

    ctx.fillRect(x, y, 10, 10);

    if(x>w || x<0){ xd = -xd }
    if(y>h || y<0){ yd = -yd }

    x += xd;
    y += yd;
}

setup();
setInterval(draw, 1000/60);

here's the above as a fiddle: http://jsfiddle.net/o56enw48/

sometimes i've even seen a third function added to this equation, something like setup, render, animate like this: http://jsfiddle.net/o56enw48/1/ ( very common in threejs examples )

but it seems to me all you really need is that draw ( looping ) function, like this:

var ctx, w, h,
    x = y = 1,
    xd = yd = 1;

var canvas = document.getElementById("canvas");
    canvas.width = w = window.innerWidth;
    canvas.height = h = window.innerHeight;

ctx = canvas.getContext("2d");


function draw() {
    ctx.clearRect(0, 0, w, h);

    ctx.fillRect(x, y, 10, 10);

    if (x > w || x < 0) { xd = -xd }
    if (y > h || y < 0) { yd = -yd }

    x += xd;
    y += yd;
}

setInterval(draw, 1000 / 60);

fiddle for the above here: http://jsfiddle.net/o56enw48/2/

i realize there must be some practical/functional explanation for why my first example seems to be the convention ( across languages ), just not sure why????

Nick Briz
  • 1,917
  • 3
  • 20
  • 34
  • It's all to do with code reusability. If you want to change the height or width of your canvas for example, you have to retype out all those lines of code after you change the size, or you can just run `setup()` again. Which is the same reason that the drawing details are in a function, because they are called over and over again. – James Hay Aug 14 '14 at 22:24
  • It's a form of code organization. Using the function name `setup` clearly indicates the intend of these lines. – Felix Kling Aug 14 '14 at 22:25
  • Note that `y` and `yd` are not declared with `var`. – elclanrs Aug 14 '14 at 22:28

0 Answers0