It's time to clean up that code, and I'm going to walk through those changes here as I make them. My goals for this exercise are a little more focused because I don't expect to have many issues with the formatting or naming this time around. The code is too recent for that, as I tend to be happy with the formatting and naming of my more recent code. I do expect to address the following issues, though:
- There was a problem with activating animations on touch screens that should be fixed.
- There are magic numbers all over the place. Those should be contained in constants and configurations. Shame on me
- There's duplication all over the place; shame on me again (and again and again).
Fixing Touchscreen Support
As it turns out, I already have a small, ugly start to the API because at some point during the writing of the DSP series, I got tired of copying all of that code from one graph to another and seeing it bloat more and more. I started pulling out some of the easiest, most used functions into a separate include file. This file lives in my github.io repo as dsp_graphing.js, and it contains some useful functions for drawing different types of axes and a sine curve generator. It's a start, but it's filled with magic numbers specific to drawing graphs at the size I was using for my blog posts, and, well, yeah, it's really ugly. We'll fix it up, though. The github.io repo will show the refactorings that were done to improve it.
Before we get into the nitty-gritty of refactoring and fleshing out the API, I want to fix that first issue of my graphs not reacting to touch events. I spent a lot of time trying to figure this out the first time writing all of these DSP posts, and I spent a fair amount of time again now, finally figuring it out. Like all good bugs, it was pretty simple in the end. It turns out I was trying to attach an event handler to a canvas event that didn't exist.
How did this happen? Well, PixiJS allows you to add event handlers to different drawing objects in the canvas you're drawing on, and the events have names like 'click' for a mouse click or 'tap' for a touchscreen tap. I was using these names, but I was attaching the handlers to the canvas instead of a PixiJS drawing object because I couldn't get the events to work when I attached the handlers to a drawing object. The 'click' event happened to work because it's the same name for the HTML5 canvas, but the corresponding 'tap' event for the canvas is 'touchend'. Once I figured that out and made the fix, I finally had support for touch screens. Here's what the initialization code looks like for starting up PixiJS on a canvas and adding events:
$(function() {
  var canvas = $('#canvas-sine-offset');
  var renderer = PIXI.autoDetectRenderer(canvas.width(), canvas.height(), { antialias: true });
  canvas.append(renderer.view);
  canvas.on('click', onClick);
  canvas.on('touchend', onClick);
  $('canvas').css('border-radius', 5);
  
  // ...
});function initCanvas(id, eventHandler) {
  var canvas = $(id);
  var renderer = PIXI.autoDetectRenderer(canvas.width(), canvas.height(), { antialias: true });
  canvas.append(renderer.view);
  canvas.on('click', eventHandler);
  canvas.on('touchend', eventHandler);
  $('canvas').css('border-radius', 5);
  return renderer;
}  var renderer = initCanvas('#canvas-sine-offset', onClick);var dsp_graph = (function() {
  return {
    initCanvas: function(id, eventHandler) {
      var canvas = $(id);
      var renderer = PIXI.autoDetectRenderer(canvas.width(), canvas.height(), { antialias: true });
      canvas.append(renderer.view);
      canvas.on('click', eventHandler);
      canvas.on('touchend', eventHandler);
      $('canvas').css('border-radius', 5);
      return renderer;
    }
  }
}());Refactoring the Current API
Things are already looking better. Now it's time to tackle the current API monstrosity and make it a little more sane. The main part of the API is a set of four functions that draw different types of axes for the graphs. The first one is drawPositiveAxis():
    drawPositiveAxis: function(stage, x_labels, y_labels) {
      var graphics = new PIXI.Graphics();
      graphics.lineStyle(1, 0xdddddd, 1);
      graphics.moveTo(15, 280);
      graphics.lineTo(535, 280);
      for(var x = 41; x <= 535; x += 26) {
        graphics.moveTo(x, 275);
        graphics.lineTo(x, 280);
      }
      graphics.moveTo(15, 20);
      graphics.lineTo(15, 280);
      for(var y = 20; y < 280; y += 26) {
        graphics.moveTo(15, y);
        graphics.lineTo(20, y);
      }
      stage.addChild(graphics);
      var label_style = { font: '10px Arial', fill: '#eeeeee' };
      var axis_style = { font: 'italic 14px Arial', fill: '#eeeeee' };
      if (typeof x_labels != 'undefined') {
        var x = 55;
        var step = 52;
        x_labels.forEach(function(label) {
          var text = new PIXI.Text(label, label_style)
          text.x = x
          text.y = 282
          stage.addChild(text)
          x += step
        })
      } else {
        var x_text = new PIXI.Text('t', axis_style);
        x_text.x = 540;
        x_text.y = 272;
        stage.addChild(x_text);
      }
      if (typeof y_labels != 'undefined') {
        var y = 223;
        var step = 52;
        y_labels.forEach(function(label) {
          var text = new PIXI.Text(label, label_style)
          text.x = 2
          text.y = y
          stage.addChild(text)
          y -= step
        })
      } else {
        var y_text = new PIXI.Text('f(t)', axis_style);
        y_text.x = 10;
        y_text.y = 2;
        stage.addChild(y_text);
      }
    },  function drawXAxis(graphics, start, end, y) {
      graphics.moveTo(start, y);
      graphics.lineTo(end, y);
      for(var x = start+TICK_STEP; x <= end; x += TICK_STEP) {
        graphics.moveTo(x, y-TICK_SIZE);
        graphics.lineTo(x, y);
      }
      graphics.moveTo(X_AXIS_MID, y - 2*TICK_SIZE);
      graphics.lineTo(X_AXIS_MID, y);
  }
  function drawYAxis(graphics, start, end, x, offset) {
      graphics.moveTo(x, start);
      graphics.lineTo(x, end);
      for(var y = start+offset; y <= end; y += TICK_STEP) {
        graphics.moveTo(x, y);
        graphics.lineTo(x+TICK_SIZE, y);
      }
  }  const AXIS_COLOR = 0xdddddd;
  const TICK_SIZE = 5;
  const TICK_STEP = 26;
  const X_AXIS_START = 15;
  const X_AXIS_MID = 275;
  const X_AXIS_END = 535;
  const Y_AXIS_START = 20;
  const Y_AXIS_MID = 150;
  const Y_AXIS_END = 280;    drawPositiveAxis: function(stage, x_labels, y_labels) {
      var graphics = new PIXI.Graphics();
      graphics.lineStyle(1, AXIS_COLOR, 1);
      drawXAxis(graphics, X_AXIS_START, X_AXIS_END, Y_AXIS_END);
      drawYAxis(graphics, Y_AXIS_START, Y_AXIS_END, X_AXIS_START, 0);
      stage.addChild(graphics);  const LABEL_STYLE = { font: '10px Arial', fill: '#eeeeee' };
  const AXIS_TITLE_STYLE = { font: 'italic 14px Arial', fill: '#eeeeee' };
  const X_AXIS_TITLE_X = 540;
  const X_AXIS_TITLE_Y_LOW = 272;
  const X_AXIS_TITLE_Y_MID = 142;
  const X_AXIS_TITLE_Y_HIGH = 77;
  const X_AXIS_LABEL_X = 273;
  const X_AXIS_LABEL_Y_MID = 152;
  const X_AXIS_LABEL_Y_HIGH = 87;
  const Y_AXIS_TITLE_X = 10;
  const Y_AXIS_TITLE_Y = 2;
  function drawXTitle(stage, y) {
    var x_text = new PIXI.Text('t', AXIS_TITLE_STYLE);
    x_text.x = X_AXIS_TITLE_X;
    x_text.y = y;
    stage.addChild(x_text);
  }
  function drawXLabel(stage, y) {
    var xLabel = new PIXI.Text('1', { font: '14px Arial', fill: '#eeeeee' });
    xLabel.x = X_AXIS_LABEL_X;
    xLabel.y = y;
    stage.addChild(xLabel);
  }
  function drawXLabels(stage, labels) {
    var step = 2*TICK_STEP;
    var x = step + 3;
    labels.forEach(function(label) {
      var text = new PIXI.Text(label, LABEL_STYLE);
      text.x = x;
      text.y = Y_AXIS_END + 2;
      stage.addChild(text);
      x += step;
    });
  }
  function drawYTitle(stage) {
    var y_text = new PIXI.Text('f(t)', AXIS_TITLE_STYLE);
    y_text.x = Y_AXIS_TITLE_X;
    y_text.y = Y_AXIS_TITLE_Y;
    stage.addChild(y_text);
  }
  function drawYLabels(stage, labels) {
    var step = 2*TICK_STEP;
    var y = Y_AXIS_END - step - 5;
    labels.forEach(function(label) {
      var text = new PIXI.Text(label, LABEL_STYLE);
      text.x = 2;
      text.y = y;
      stage.addChild(text);
      y -= step;
    });
  }    drawPositiveAxis: function(stage, x_labels, y_labels) {
      var graphics = new PIXI.Graphics();
      graphics.lineStyle(1, AXIS_COLOR, 1);
      drawXAxis(graphics, X_AXIS_START, X_AXIS_END, Y_AXIS_END);
      drawYAxis(graphics, Y_AXIS_START, Y_AXIS_END, X_AXIS_START, 0);
      stage.addChild(graphics);
      if (typeof x_labels != 'undefined') {
        drawXLabels(stage, x_labels);
      } else {
        drawXTitle(stage, X_AXIS_TITLE_Y_LOW);
      }
      if (typeof y_labels != 'undefined') {
        drawYLabels(stage, y_labels);
      } else {
        drawYTitle(stage);
      }
    }That pretty much wraps up the refactoring of the current DSP graphing API. Between that cleanup and fixing the issue with touchscreen support, we're already making noticeable improvements. After checking that the graphs still look right in my graph inspection pages and committing the code, I'm ready to update all of those blog posts with the new code. Next time we'll start walking through the code in each post and seeing what can be extracted into the API and shared between all of the graphs. I bet we don't get too far before we find some significant improvements.
No comments:
Post a Comment