jstuartj.com

Home of J. Stuart J. Creative
The Minneapolis skyline with Stone Arch bridge in foreground.

Mapping a range of values to a defined index.

I’m researching options for an easy to edit, responsive image map solution for WordPress.

I’ve looked at SVG, however it can get tricky to edit, especially with complicated maps or floor plans. It also requires vector software such as Adobe Illustrator, Inkscape or one of several Mac solutions which I don’t have access to. I’m also not sure if you can define XLINK tags or assign IDs or if it would require manual editing.

So, I’m thinking of using canvas and two images: One to define the map, the other a color map defining the regions. This would allow users to upload a PNG or JPG. It would also be easy to make responsive, swap regions and the color map could be used to drive an effect on touch/hover.

While working on a proof of concept, I needed to map an array of values ranging from 0 -255 to an index of = 0 – 100; below is my basic solution in JavaScript.

/**
 * Maps an array of int values from (0 to 255) to an index from (0-100).
 * @param array int
 * @return array int
 */

function mapValueToIndex(oldValues) {
 
  //* Set  the old and new range for conversion.
  var oldMin = 0,
    oldMax = 255,
    newMin = 0,
    newMax = 100,
    newValues = [],
    count = oldValues.length;
  
  for (i = 0; i < count; i++) {
    if ( isNaN(oldValues[i]) == false ){
    	newValue = (((oldValues[i] - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin;
    	newValues[i] = Math.round(newValue);  
    } 
  }
  
  return newValues;

}
Copyright © 2024, J. Stuart Johnson