WEBDOOD.COM

Javascript

<CANVAS> Spinner Revisited

by webdood on Jul.11, 2012, under Canvas, Javascript, Software Development

I previously invented a Javascript-only, CANVAS-based spinner. I went to re-use this code today and found it to be less than easy to use.

Therefore, I rejiggered a few things to make it so you can create an number of spinners on page, with each spinner having its own start, stop, display and toggle method exposed.

      function Spinner( oHTMLElement, params ) {
        if (typeof(oHTMLElement)=="string")  { oHTMLElement = document.getElementById(oHTMLElement); }
        if (oHTMLElement) {
          if (params===undefined) { params={} };
          var oCanvas = document.createElement('canvas'),
              context = null,
              height = parseFloat( getComputedStyle( oHTMLElement, null)["height"] ),
              width  = parseFloat( getComputedStyle( oHTMLElement, null)["width"] ),
              radius = Math.min(height / 2, width / 2),
              innerRadius     = params["innerRadius"] || radius * 2 * .27833333,
              outerRadius     = params["outerRadius"] || radius * .99,
              finWidth        = params["finWidth"]    ||  .08 * radius,
              finColors       = params["finColors"]   || [ "e8e8e8","f1f1f1", "fafafa", "b2b2b2", "b6b6b6", "b9b9b9", "bebebe", "c3c3c3", "c9c9c9", "d0d0d0", "d7d7d7", "dfdfdf" ],
              strokeStyle     = params["strokeStyle"] || "rgba(128,128,128,1)",
              strokeWidth     = (params["strokeWidth"]!==undefined) ? params["strokeWidth"] : 2,    // Specifies whether an outline will appear around each fin
              finColorOffset  = 0,      // This is a counter that is mod-ed around 12 to draw the spinner with appropriate color as indexed into the finColors array
              spinnerInterval = null;   // Handle to setInterval operation generating spin animation
          // Set up the <canvas> object
          oCanvas.width  = width;
          oCanvas.height = height;
          context  = oCanvas.getContext('2d');
          context.translate( radius, radius );
          oHTMLElement.appendChild( oCanvas );
          draw();
        }
        ///////////////////////////////////////////////////////////////////////////////////
        // Spinner.display(boolean bDisplay) - show/hides the parent oHTMLElement        //
        // =================================   (external method)                         //
        ///////////////////////////////////////////////////////////////////////////////////
        this.display = function( bDisplay ) {
          if ( bDisplay ) {
            oHTMLElement.style.display = 'block';
          } else {
            oHTMLElement.style.display = 'none';
          }
        }
        ///////////////////////////////////////////////////////////////////////////////////
        // draw() - this clears the previous spinner drawn, then loops through the       //
        // ======   12 fins, rotating the canvas 30 degrees each time and drawing each   //
        // fin with the appropriate color from the finColors array (internal method)     //
        ///////////////////////////////////////////////////////////////////////////////////
        function draw() {
          context.clearRect(-width,-height,width*2,height*2);
          for (var i=0;i<12;i++) {
            drawFin( finColors[ (i + finColorOffset) % 12] );
            context.rotate(-360/12 * Math.PI/180);
          }
        }
        ///////////////////////////////////////////////////////////////////////////////////
        // drawFin( string fillColor ) - this draws a single fin.  Each is made up of a  //
        // ==========================   half circle on either end of a rectangle.        //
        //  Trust me, this took a while to work out. But I overcame! (internal method)   //
        ///////////////////////////////////////////////////////////////////////////////////
        function drawFin( fillColor ) {
          var ctx = context;
          ctx.fillStyle = fillColor;
          ctx.strokeStyle = strokeStyle;
          ctx.lineWidth   = strokeWidth;
          ctx.beginPath();
          ctx.arc(outerRadius-finWidth,0,finWidth,-Math.PI/2,Math.PI/2, false);
          ctx.rect(innerRadius,-finWidth,outerRadius-innerRadius-finWidth,finWidth*2);
          ctx.arc(innerRadius,0,finWidth,Math.PI/2,-Math.PI/2,false);
          ctx.closePath();
          if (strokeWidth > 0) {
            ctx.stroke();
          }
          ctx.fill();
        }
        ///////////////////////////////////////////////////////////////////////////////////
        // Spinner.start() - sets up an interval that continues to call spin().          //
        // ===============   (external method)                                           //
        ///////////////////////////////////////////////////////////////////////////////////
        this.start = function() {
          this.display( true );
          spinnerInterval = setInterval( function() { spin(); }, 100);
        }
        ///////////////////////////////////////////////////////////////////////////////////
        // Spinner.stop() - cancels the interval used to continuously call spin().       //
        // ==============   (external method)                                            //
        ///////////////////////////////////////////////////////////////////////////////////
        this.stop = function() {
          clearInterval( spinnerInterval );
          spinnerInterval = null;
        }
        ///////////////////////////////////////////////////////////////////////////////////
        // spin() - this increments the offset into the fin color array. Really, the     //
        // ======   spinner is not "spinning", per se, but rather re-drawing the fins    //
        // in-place with a set of continuously changing colors.  (internal method)       //
        ///////////////////////////////////////////////////////////////////////////////////
        function spin() {
          finColorOffset += 1;
          draw();
        }
        this.toggle = function() {
          if (spinnerInterval === null) {
            this.start();
          } else {
            this.stop();
          }
        }
      }

Please give credit when you steal this!
by Shannon Norrell, 2010-2012

Working Example

Leave a Comment more...

Javascript animateObjectFromTo

by webdood on Jul.04, 2012, under Javascript, Objects, Software Development

This method will animate an object from a given left, top to another left, top over a specified number of milliseconds at a specified frame rate.

This is an example of how it might be called:

  var myDiv = document.getElementById('myDiv),
      currentPosition = window.getComputedStyle(myDiv,null),
      currentLeft     = parseFloat(currentPosition["left"]),
      currentTop      = parseFloat(currentPosition["top"]);
  animateObjectFromTo(
    myDiv,
    { top:currentTop, left:currentLeft },
    { top:0, left:currentLeft },
    250
  );

Notice how the method uses an inner function for the animation heavy lifting.

///////////////////////////////////////////////////////////////////////////////////////////
//  animateObjectFromTo([object|string] oHTMLElement, json From, json To, int totalTimeInMilliseconds, OPTIONAL int framesPerSecond)
//   Sets up an animation that interpolates frame animation from a beginning top, left coordinate
//   to an ending top, left coordinate over a number of milliseconds at a specified frame rate
//      totalTimeInMilliseconds - default is 1 second
//      framesPerSecond - default is 30
/////////////////////////////////////////////////////////////////////////////////////////
    animateObjectFromTo : function(oHTMLElement, from, to, totalTimeInMilliseconds, framesPerSecond) {
      if (typeof(oHTMLElement)=="string")  {
        oHTMLElement = document.getElementById(oHTMLElement);
      }
      totalTimeInMilliseconds = totalTimeInMilliseconds || 1000;
      framesPerSecond = framesPerSecond || 30;
      var currentFrame      = 0,
          numberOfFrames    = parseInt(totalTimeInMilliseconds / framesPerSecond),
          deltaTimePerFrame = totalTimeInMilliseconds/numberOfFrames,
          deltaXPerFrame    = (to.left - from.left)/numberOfFrames || 0,
          deltaYPerFrame    = (to.top - from.top)/numberOfFrames || 0;

      animate();

      function animate() {
        if (currentFrame<numberOfFrames) {
          var oCurrentStyle = document.defaultView.getComputedStyle(oHTMLElement, null);
          oHTMLElement.style.left = parseFloat(oCurrentStyle["left"]) + deltaXPerFrame + "px";
          oHTMLElement.style.top  = parseFloat(oCurrentStyle["top"]) + deltaYPerFrame + "px";
          currentFrame += 1;
          setTimeout( function() { animate(); }, deltaTimePerFrame );
        }
      }

shannon norrell

Leave a Comment more...

Javascript String Ellipse to Length

by webdood on Apr.10, 2012, under Canvas, Javascript, Software Development, Strings

A perennial problem with HTML is correctly dealing with ellipsis on text. There is the text-overflow:ellipsis trick, but there are some situations where you need to ellipse a string at a certain number of pixels.

I think I have come up with a pretty clever solution to this.
By adding a prototype to the String Object and using a dynamically generated <canvas> tag, we can accurately measure the width of a string based on a provided font and fontSize, adding ellipsis as necessary.

UPDATE

I was asked by an associate if there was a way to retain the original value of the string before it was ellipsed. In answer to that, I added the lines in red.
Now there is a property called “.originalValue” added to each string that has been ellipsed.

////////////////////////////////////////////////////////////////////////////////
//
// String.ellipseToLength(int length, OPTIONAL string fontSize, OPTIONAL string fontFamily)
// ======================
// Returns an ellipsed string measured to length using CANVAS's measureText method
// By passing in fontSize and FontFamily, you will get accurate measurements
//
////////////////////////////////////////////////////////////////////////////////
String.prototype.ellipseToLength = function( length, fontSize, fontFamily) {
  var bContinue = true,
      ctx = document.createElement('canvas').getContext('2d'),
      measuredLength,
      originalValue = retVal = this.toString(),
      firstChar = retVal.charAt(0);
  fontSize    = (typeof fontSize==="undefined") ? "12pt" : fontSize;
  fontFamily  = (typeof fontFamily==="undefined") ? "Arial" : fontFamily;
  ctx.font = fontSize + " " + fontFamily;
  if ((typeof length==="undefined") || length===0 || retVal.length===0 || ctx.measureText(firstChar).width >= length) {   // Special weird case the first character is greater than the length asked for ...
    retVal = "...";
  } else {
    measuredLength = ctx.measureText(retVal).width;
    if (measuredLength > length) {  // If the measured length of the string is larger than that specified, then more work is required
      while (bContinue) {
        retVal = retVal.slice(0,-1);
        measuredLength = ctx.measureText(retVal + '...').width;
        if (measuredLength <= length) {
          retVal = retVal + '...';
          bContinue = false;
        }

        if (retVal.length===0) {
          retVal = "..."
          bContinue = false;
        }
      }
    }
  }
  retVal.__proto__.originalValue = originalValue;
  return retVal;
}
Leave a Comment more...

Javascript Number roundToPrecision

by webdood on Nov.17, 2011, under Javascript, Numbers

Needed a cross-browser function round to a given precision. Cannot rely on toFixed()

Number.prototype.roundToPrecision = function( precision ) {
  if (precision===undefined) { precision = 2; }
  var multiplier = Math.pow(10,precision);
  return Math.round(this*multiplier)/multiplier;
}
Leave a Comment more...

Javascript Number ensureDecimalPlaces

by webdood on Nov.17, 2011, under Arrays, Javascript, Numbers

Needed a function ensure that a certain number of digits appeared after a decimal point today.

For instance 1.3 should be 1.300, 1 should be 1.000 etc.

Number.prototype.ensureDecimalPlaces = function( decimals ) {
  var tempString = this.toString(),
      pileOfPads = "000000000000000000000000",
      decimalLocation = tempString.indexOf('.');
  if (decimalLocation === -1) {
    retVal = tempString + '.' + pileOfPads.substring(0,decimals);
  } else {
    retVal = tempString + pileOfPads;
    retVal = retVal.substring(0,decimalLocation+decimals+1);
  }
  return retVal;
}

Example use:

var x = 12.3
console.log(x.ensureDecimalPlaces(3)) returns 12.300

Leave a Comment more...

HTML5 Canvas – Drawing Dashed Lines (dashedLineFromTo)

by webdood on Jul.18, 2011, under Canvas, HTML5, Javascript

There is no way built-in way to draw dashed lines using <canvas>.
Therefore, I came up with a prototype method that hangs off of the CanvasRenderingContext2D Object that I am calling “dashedLineFromTo”

As you may expect, it simply draws a bit of a line, then skips a bit and draws more until it is done “connecting the dots” between point A and B.

My particular application involves generating a line graph with dashed lines.
This is, in effect, a series of dashed lines and adds a slight nuance inasmuch as when one dashed line is completed and another picks up where it left off, we must keep track of if the previous line ended in a lineTo (ie drawn pixels) or a moveTo (ie just moving the drawing cursor) and, with the new line segment, begin it with a lineTo or a moveTo to “finish off” the pixels that were left unpainted in the previous segment.

This sounds more complicated than it is.

    var __dashedLineFromTo = {
      isDrawing : true,
      unFinishedPixelsFromLastDash : 0
    }
    CanvasRenderingContext2D.prototype.dashedLineFromTo = function(from,to) {
      var x=from[0], y=from[1],
          dashLength        = 2,
          dx                = (to[0] - x) + .00000001,
          dy                = to[1] - y,
          slope             = dy/dx,
          distanceRemaining = Math.sqrt(dx*dx + dy*dy),
          bUnfinishedPixels = false,
          theDashLength,
          xStep;
      this.moveTo(x,y);
      while (distanceRemaining>=0.1) {
        if (__dashedLineFromTo.unFinishedPixelsFromLastDash === 0) {
          theDashLength = dashLength;
        } else {
          theDashLength = __dashedLineFromTo.unFinishedPixelsFromLastDash;
          __dashedLineFromTo.unFinishedPixelsFromLastDash = 0;
          __dashedLineFromTo.isDrawing = !__dashedLineFromTo.isDrawing
        }
        if (dashLength > distanceRemaining) { dashLength = distanceRemaining; bUnfinishedPixels=true; }
        xStep = Math.sqrt( theDashLength*theDashLength / (1 + slope*slope) );
        x += xStep;
        y += slope*xStep;
        this[__dashedLineFromTo.isDrawing ? 'lineTo' : 'moveTo'](x,y);
        distanceRemaining -= theDashLength;
        __dashedLineFromTo.isDrawing = !__dashedLineFromTo.isDrawing;
      }
      if (bUnfinishedPixels) {
        __dashedLineFromTo.unFinishedPixelsFromLastDash = theDashLength;
      }
    }
    function init() {
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      ctx.beginPath();
      ctx.lineWidth = 2;
      ctx.lineCap = 'butt';
      ctx.beginPath();
      ctx.dashedLineFromTo([0.2, 1.2], [99.9, 12.8]);
      ctx.dashedLineFromTo([99.9, 12.8], [118.5, 5.0]);
      ctx.dashedLineFromTo([118.5, 5.0], [148.5, 105.0]);
      ctx.dashedLineFromTo([148.5, 105.0], [178.5, 55.0]);
      ctx.dashedLineFromTo([178.5, 55.0], [218.5, 97.3]);
      ctx.closePath();
      ctx.stroke();
    }
<body onload="init()">
   <canvas id="canvas" width="912" height="339"></canvas>
 </body>

Here is a working example:

Shannon Norrell

3 Comments more...

Javascript Array Sort By String Length

by webdood on Jul.08, 2011, under Arrays, Javascript

Had a need to sort an array of strings by length of each string in descending order.
Simple solution, really. Perhaps may come in handy at a later date.

  ////////////////////////////////////////////////////////////////////////////
  //
  // Array.sortByStringLength() - sorts an array of strings based on length
  // ==========================
  //
  ////////////////////////////////////////////////////////////////////////////
  Array.prototype.sortByStringLength = function() {
    return this.sort( byStringLength )
  }
  function byStringLength(a,b) {//Sort function used by Array.sortByStringLength
    var retVal = 0;
    if (a.length > b.length) { retVal = -1; }
    return retVal;
  }

Shannon Norrell

2 Comments more...

Determine if an Object is empty in Javascript

by webdood on Apr.22, 2011, under Javascript, Objects

There are times when you need to determine if an object actually contains anything.
Distinguishing {} from { foo:bar } cannot be done by checking for .length, as an Object does not provide that.

Therefore, the only way to determine if there is anything in the Object is to basically do a for-each loop on the Object itself. Now, depending on the Javascript library you are (probably) using, there will be lots of *stuff* inside the Object that was inherited from the prototype chain. Since we are looking for actual stuff, we utilize the rarely used hasOwnProperty method to determine if the *stuff* in the Object was inherited or actually a part of theObject itself.

Now, you could add this to the prototype of Object itself (for instance Object.prototype.isEmpty = function() { blah};, but I consider that bad practice as – particularly with the Object Object, from which every other type of *thing* in Javascript inherits, the prototype wil be added to all other types of Objects in Javascript as well (for instance String would then have an isEmpty method).

This is all fine and dandy if you want to “robustify” this to support all data types, but trust me, it’s much cleaner and nicer to the DOM
to do it the way I illustrate below.

////////////////////////////////////////////////////////////////////////////////
//
// objectIsEmpty( object) - determines if an Object is empty
// ======================
//   You could add this to the prototype chain of Object as .isEmpty(),
//   but that would be wasteful. Better to keep it as a standalone function
//
////////////////////////////////////////////////////////////////////////////////
function objectIsEmpty( oObject ) {
  var eachProperty = null;
  for (eachProperty in oObject) {
    if (oObject.hasOwnProperty(eachProperty)) {
      return false;
    }
  }
  return true;
}

Shannon Norrell

Leave a Comment more...

Javascript Array.remove and Array.indexOf methods

by webdood on Jan.01, 2011, under Javascript, Software Development

I kept finding myself needing to remove items from an array, so developed a quick helper (prototype) method attached to the Array Object to help.
////////////////////////////////////////////////////////////////////////////////
//
// Array.remove( object|string item) - removes an item from an array
//    Example x = ["abc","xyz",1,4]  x.remove("xyz") returns ["abc",1,4]
//    Presumably this will eventually be added to Javascript, but until that day...
////////////////////////////////////////////////////////////////////////////////
if (Array.prototype.remove===undefined) {
  Array.prototype.remove = function( item ) {
    var itemLocation = this.indexOf(item);
    if (itemLocation > -1) {
      this.splice(itemLocation,1);
    }
  }
}
////////////////////////////////////////////////////////////////////////////////
//
// Array.indexOf() - returns integer index where valueToSearchFor is in an Array
//   (believe it or not, not all browsers have this yet ... and it's 2010!
////////////////////////////////////////////////////////////////////////////////
if (Array.prototype.indexOf===undefined) {
  Array.prototype.indexOf = function( valueToSearchFor ) {
    var iEnd = this.length;
    var retVal = -1;
    for (var i=0;i<iEnd; i++) {
      if (this[i] == valueToSearchFor) {
        retVal = i;
        break;
      }
    }
    return retVal;
  };
}

Shannon Norrell

Leave a Comment :, , more...

Javascript Array Detection

by webdood on Oct.06, 2010, under Javascript, Software Development

Turns out the most reliable way to detect an Array is not to use the old standby:

return (typeof foo === ‘object’ && foo.constructor === Array)

but rather to do this:

function isArray(anArray) {
  return Object.prototype.toString.apply(anArray) === "[object Array]";
}

I have to give credit to my friend Doug Crockford, for this.

I recommend his book Javascript: The Good Parts

shannon norrell

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org