Created
August 5, 2016 09:42
-
-
Save doxas/da7bb963960583fa5dfa967802e7e7de to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ColorMap(width, height, value){ | |
var i, j, k, l, f; | |
var c, cx, gr, cs, imageData; | |
var min, max; | |
var arr; | |
// arguments check | |
if(Object.prototype.toString.call(value) !== '[object Array]'){return null;} | |
if(value.length < 2){return null;} | |
f = true; | |
for(i = 0, j = value.length; i < j; ++i){ | |
f = f && (value[i] && value[i].hasOwnProperty('value') && value[i].hasOwnProperty('color')); | |
} | |
if(!f){return null;} | |
// colorstop array sort | |
arr = value.sort(function(a, b){return a.value - b.value;}); | |
if(arr[0].value >= arr[arr.length - 1].value){return null;} | |
min = arr[0].value; | |
max = arr[arr.length - 1].value; | |
// create canvas and gradient | |
c = document.createElement('canvas'); | |
cx = c.getContext('2d'); | |
if(!cx){return null;} | |
c.width = width; | |
c.height = height; | |
gr = cx.createLinearGradient(0, 0, width, height); | |
// add color stop | |
for(i = 0, j = arr.length; i < j; ++i){ | |
k = Math.min(Math.max(arr[i].value / max, 0.0), 1.0); | |
cs = gr.addColorStop(k, arr[i].color); | |
} | |
cx.fillStyle = gr; | |
cx.rect(0, 0, width, height); | |
cx.fill(); | |
imageData = cx.getImageData(0, 0, width, height); | |
return { | |
data: imageData.data, | |
path: c.toDataURL() | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment