diff options
Diffstat (limited to 'js/color_code.js')
| -rw-r--r-- | js/color_code.js | 113 |
1 files changed, 113 insertions, 0 deletions
diff --git a/js/color_code.js b/js/color_code.js new file mode 100644 index 0000000..f16e91c --- /dev/null +++ b/js/color_code.js @@ -0,0 +1,113 @@ + +var MircColor = (function(){ + var COLORS = [ + [255,255,255], + [0,0,0], + [0,0,127], + [0,147,0], + [255,0,0], + [127,0,0], + [156,0,156], + [252,127,0], + [255,255,0], + [0,252,0], + [0,147,147], + [0,255,255], + [0,0,252], + [255,0,255], + [127,127,127], + [210,210,210] + ] + + function closest_to(pixel){ + return COLORS.reduce(function(prev, curr, index) { + var d = distance(pixel, curr) + if (prev[0] > d) { + prev[0] = d + prev[1] = index + } + return prev + }, [Infinity, -1])[1] + } + + function distance(u, v){ + var r = u[0] - v[0] + var g = u[1] - v[1] + var b = u[2] - v[2] + return Math.sqrt(r*r+g*g+b*b) + } + + function fromImageData (pixels, cb){ + var rows = [], + pixel = new Array (4), + data = pixels.data, + t + console.log(pixels) + for (var i = 0, h = pixels.height; i < h; i++) { + var row = [] + rows.push(row) + for (var j = 0, w = pixels.width; j < w; j++) { + t = (i*w+j)*4 + pixel[0] = data[t] + pixel[1] = data[t+1] + pixel[2] = data[t+2] + pixel[3] = data[t+3] + row[j] = closest_to(pixel) + } + } + console.log(rows) + if (! cb) return rows + else cb (rows) + } + function fromUrl (url, cb, width) { + var img = new Image () + img.onload = function(){ + var canvas = document.createElement("canvas"), ctx = canvas.getContext('2d') + if (width) { + canvas.width = width + canvas.height = img.naturalHeight * width / img.naturalWidth / 2 + } + else { + canvas.width = img.naturalWidth * 2 + canvas.height = img.naturalHeight + } + ctx.drawImage(img,0,0,img.naturalWidth,img.naturalHeight,0,0,canvas.width,canvas.height) + var pixels = ctx.getImageData(0,0,canvas.width,canvas.height) + fromImageData(pixels, cb) + } + img.src = url + } + function ascii (rows) { + var lines = rows.map(function(str){ + return str.map(function(index){ return "\\x03" + index + "," + index + "x\\x03" }).join("") + }).join("\\n") + var txt = '/exec -out printf "' + lines + '"\n' + return txt + } + function asciiFromUrl (url, cb, width) { + fromUrl(url, function(rows){ + cb(ascii(rows), rows) + }, width) + } + function stringFromUrl (url, cb, width) { + fromUrl(url, function(rows){ + cb(rows.map(function(str){ + return str.map(function(index){ return "\C-c" + index + "," + index + "x\C-c" }).join("") + }).join("\n")) + }, width) + } + + return { + colors: COLORS, + closest_to: closest_to, + distance: distance, + fromUrl: fromUrl, + fromImageData: fromImageData, + stringFromUrl: stringFromUrl, + asciiFromUrl: asciiFromUrl, + ascii: ascii, + } + +})() + + |
