WEBDOOD.COM

Canvas

<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 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...

HTML5 Green Screen Technique using <VIDEO> and <CANVAS>

by webdood on Sep.09, 2011, under Canvas, HTML5, Safari-Specific, Software Development

This technique allows you to composite a green-screen video over a web page.
The basic setup consists of a hidden <VIDEO> tag, another hidden <CANVAS> tag, where each frame of video is captured for further processing and a visible <CANVAS> tag where each processed frame is displayed.
When a frame of video is captured and placed into our “canvasProcessor”, each pixel is analyzed in turn. A pixel is represented by a CanvasPixelArray consisting of four values: (R)ed, (G)reen, (B)lue and (A)lpha.
When we find a pixel that fits in the range of “green”, we change that one to have a 0 (A)lpha value (and thus it becomes invisible).

Here is link to a working example.

<!DOCTYPE HTML><
<html>
<head>
  <title>Green Screen Test</title>
  <script type="text/javascript">
    greenScreenEngine = {
      _animator : null,
      _canvasProcessorContext : null,
      _canvasTargetContext : null,
      _height : 0,
      _width : 0,
      _video : null,
      handlerFor : {
        pause : function() {
          clearTimeout( this._animator );
        },
        play : function() {
          greenScreenEngine.parseAndProcessFrame();
        }
      },
      parseAndProcessFrame : function() {
        if (this._video.paused || this._video.ended) {
          return;
        }
        this._canvasProcessorContext.drawImage(this._video,0,0,this._width,this._height)
        var videoFrame     = this._canvasProcessorContext.getImageData(0,0,this._width,this._height),
            numberOfPixels = videoFrame.data.length / 4;
        for (var i=0;i 100 && b < 100) {      // Here we look for what we perceive to be a green pixel
            videoFrame.data[i * 4 + 3] = 0;        // If we find one, make its alpha channel transparent
          }
        }
        this._canvasTargetContext.putImageData(videoFrame,0,0);
        this._animator = setTimeout( function() { greenScreenEngine.parseAndProcessFrame() },0);
      },
      setCanvasProcessor : function( canvasProcessorID, scale ) {
        scale = (scale!==undefined) ? scale : 1;
        this._height = this._video.videoHeight * scale;
        this._width  = this._video.videoWidth * scale;
        var oCanvas = document.getElementById(canvasProcessorID);
        oCanvas.height = this._height;
        oCanvas.width  = this._width;
        this._canvasProcessorContext = oCanvas.getContext("2d");
        this._canvasProcessorContext.drawImage(this._video,0,0,this._width,this._height)
      },
      setCanvasTarget : function( canvasTargetID ) {
        var oCanvas = document.getElementById(canvasTargetID);
        oCanvas.height = this._height;
        oCanvas.width  = this._width;
        this._canvasTargetContext =  oCanvas.getContext("2d");
      },
      setSourceVideo : function( videoID ) {
        this._video = document.getElementById( videoID );
        this._video.addEventListener("play", greenScreenEngine.handlerFor.play)
        this._video.addEventListener("pause", greenScreenEngine.handlerFor.pause)
      }
    }
    function setup() {
      greenScreenEngine.setSourceVideo("video-green-screen");
      greenScreenEngine.setCanvasProcessor("canvas-processor",.5);
      greenScreenEngine.setCanvasTarget("canvas-target");
      greenScreenEngine._video.play();
    }
  </script>
</head>
<body>
  <div>
    <video id="video-green-screen" src="talkingHead.mp4" controls="true" tabindex="0" oncanplay="setup()" style="display:none;"></video>
  </div>
  <div>
    <canvas id="canvas-processor" style="display:none;"></canvas>
    <canvas id="canvas-target" style="-webkit-transform:rotate(90deg);position:absolute;bottom:79px;"></canvas>
  </div>
</body>
</html>>

Note - For the video I've used here, I had to play with the values a bit to find just the right range of values that mean "green." Also, the source video was rotated -90deg, so I had to apply a webkit-transform to it. To see how everything works, just comment out the display:none CSS.

Shannon Norrell

1 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...

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