Separation of concerns

by Dustin Pfister

JavaScript

// the object to draw
var obj = {

  x: 0,
  y: 0,
  radius: 50,
  frame: 0,
  maxFrame: 100,
  per : 0,
  bias : 0,
  update: function(w, h) {
  
    this.per = this.frame / this.maxFrame;
    this.bias = 1 - Math.abs(this.per - .5) / .5;

    w = w || 640;
    h = h || 480;

    this.x = w / 2 - 100 + 200 * this.bias;
    this.y = h / 2;

    // step frame
    this.frame += 1;
    if (this.frame >= this.maxFrame) {

      this.frame = 0;

    }

  }

};

var obj_canvas = {

  // draw the object itself
  draw_obj: function(obj, canvas, ctx) {

    // draw a cirlce
    ctx.strokeStyle = '#ffffff';
    ctx.beginPath();
    ctx.arc(
      obj.x, // x
      obj.y, // y
      obj.radius, // radius
      0, // start radian
      Math.PI * 2 // end radian
    );
    ctx.stroke();

  },

  // draw a progress and bias bars
  draw_pb: function(obj, canvas, ctx,x,y,w,h) {
  
      x = x || 0;
      y = y || canvas.height - 10;
      w = w || canvas.width;
      h = h || 10;
      
      ctx.fillStyle = '#000000';
      ctx.fillRect(x,y,w,h);
      ctx.fillStyle = '#0000ff';
      
      // progress
      ctx.fillRect(x,y,w* (obj.frame / obj.maxFrame),h/2);
      
      // bias
      ctx.fillStyle = '#ff0000';
      ctx.fillRect(x,y+h/2,w* obj.bias,h/2);
  
  },

  // draw info about the object
  draw_info: function(obj, canvas, ctx,fs) {

    fs = fs || 15;

    ctx.strokeStyle = '#00ff00';
    ctx.textBaseline = 'top';
    ctx.font = fs+'px arial';
    ctx.strokeText('obj info: ',10,fs*1);
    ctx.strokeText('obj pos: (' + Math.floor(obj.x) + ',' + Math.floor(obj.y)+')',10,fs*2);
    ctx.strokeText('frame: ' + obj.frame + '/' +obj.maxFrame,10,fs*3);

  },

  // clear screen
  cls: function(canvas, ctx) {

    // default the canvas to a solid back background
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

  }

};

// the app
(function() {

    // create and inject a canvas
    var canvas = document.createElement('canvas'),
      ctx =...