Tuesday, January 24, 2012

Trigonometry for Web Developers, Part One

Introduction
Recently my team was tasked with developing a custom UI control for an application being built with the excellent Dojo framework.    The concept makes use of a rotatable dial, which caused some head scratching as folks hadn't used trig (trigonometry) in years.    Realizing that I could better explain the concepts by providing some "real world" examples, I put together some samples using only HTML and Javascript.  

This article is the first in a series of three, with each successive article building on the previous.    Let's get started!

Degrees vs. Radians
Most people think of angles in terms of degrees, with 360 degrees comprising a full circle.   Trig functions available in most common programming languages such as Javascript, C/C++, python, etc. all think in different units, however - these units are known as radians.    Fortunately, converting between the two is relatively easy using these formulas :
radians = (π / 180.0) * degrees
degrees = radians / (180.0 / π)
Don't let radians scare you - it's just another way of expressing the same thing and you'll like find yourself starting to "think" in radians before long. Until that time, let's create some helper functions to make things easy :
function toRadians(a_degrees)
{
  return (Math.PI / 180.0) * a_degrees;
}

function toDegrees(a_radians)
{
  return a_radians / (180.0 / Math.PI);
}
Note the use of "Math.PI" - this is a constant provided by the Javascript "Math" object that is far more precise than the typical "3.14" representation.

The diagram below demonstrates the relationship of degrees to radians, using the mathematical convention of expressing radians in terms of π.    Be sure also to notice that the circle starts from the right-most point, not the top.   This means that a line extending from the center at an angle of zero degrees/zero radians will extend to the right, not to the top, edge of the circle.


Let's Draw Something
For the purposes of demonstrating how to marry trig functions with graphics, we'll construct a simple analog-style meter in Javascript. Our meter will have a scale from 0 through 10 with tick marks for each value.     A needle will point to a value on the scale and will appear to pivot about a fixed point. We'll use Javascript to draw into an HTML canvas object, but the concepts will be the same regardless of the underlying language.

The first step is to create an HTML file to contain the page along with our Javascript.   Example 1 contains a basic HTML document along with the Javascript function DrawMeter().   When you open this file in your browser, you should see a partial circle across the top left area of your browser window, similar to the image on the right.      Go ahead and right-click to get to the "View Source" option in your browser - you'll find the helper functions for converting between degrees and radians along with the DrawMeter() function.


//---------------------------------------------------------------
function DrawMeter()
{
  var       cvs         = document.getElementById('meter'),     // Canvas object 
            centerX     = cvs.width / 2,                        // Horizontal mid-point of canvas
            bottomY     = cvs.height,                           // Bottom of canvas
            radius      = Math.min(centerX, bottomY) - 5,       // Radius of dial that fits into canvas, plus a small margin
            ctx         = cvs.getContext('2d'),                 // Graphics context for drawing
            startAngle  = toRadians(210),                       // Starting angle for scale
            endAngle    = toRadians(330);                       // Ending angle for scale
          
  // Outer edge
  ctx.beginPath();
  ctx.strokeStyle = '#777';
  ctx.arc(centerX, bottomY, radius, startAngle, endAngle, false);
  ctx.stroke();
}

This function does several interesting things.   After getting the HTML canvas element, the horizontal center and vertical bottom is found.   These values are then used to determine the radius for the meter.  The arc is then drawn representing the top of the dial, going clockwise from 210 degrees to 330 degrees, using the canvas drawing functions.

Up Next: Drawing the Tick Marks and Labels
We still have a ways to go before we having a functioning meter, but we've covered some important concepts already:
  • Degrees vs. Radians and how to convert between the two
  • Orientation of the polar coordinate system
  • Drawing an arc on an HTML canvas.

Next time, we'll draw the tick marks and labels on the meter by making use of some common trig functions to convert an angle into usable x,y coordinates.

Continue onto Part Two...

No comments:

Post a Comment