Convert a number between 1 and 16777215 to a colour value - javascript

I'm trying to convert a number between 1 and 16,777,215 to any colour format (RGB/HSL/HEX) that increments through the colour spectrum using Javascript/jQuery.
The number 16,777,215 is the total possible combinations of RGB(255,255,255) which is 32 bit colour.
I initially thought converting the value to a hex value using toString(16) would increment through the spectrum, however as the number increases it seems to work through different lightness values instead and flashes. An example of this unwanted behaviour is here http://jsfiddle.net/2z82auka/
var colour = 16777215;
window.setInterval(function(){
colour -= 1000;
$('body').css({background:'#' + colour.toString(16)});
}, 50);
How can I convert a value between 1 and 16777215 to a colour on the colour spectrum shown below?

The code below will do exactly what you want - it'll give you vibrant colors of the color spectrum exactly as the image below, and to prove it, the demo will print out the integer values beside the color. The result will look like this. Please use the rainbow function in your setInterval code.
var colours = 16777215;
function rainbow(numOfSteps, step) {
var r, g, b;
var h = 1 - (step / numOfSteps);
var i = ~~(h * 6);
var f = h * 6 - i;
var q = 1 - f;
switch(i % 6){
case 0: r = 1, g = f, b = 0; break;
case 1: r = q, g = 1, b = 0; break;
case 2: r = 0, g = 1, b = f; break;
case 3: r = 0, g = q, b = 1; break;
case 4: r = f, g = 0, b = 1; break;
case 5: r = 1, g = 0, b = q; break;
}
var c = "#" + ("00" + (~ ~(r * 235)).toString(16)).slice(-2) + ("00" + (~ ~(g * 235)).toString(16)).slice(-2) + ("00" + (~ ~(b * 235)).toString(16)).slice(-2);
return (c);
}
function render(i) {
var item = "<li style='background-color:" + rainbow(colours, i) + "'>" + i + "</li>";
$("ul").append(item);
}
function repeat(fn, times) {
for (var i = 0; i < times; i+=10000) fn(i);
}
repeat(render, colours);
li {
font-size:8px;
height:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul></ul>
(I can't take credit for this code, but I can take credit for not giving up and settling for jerky color changes. Ref: https://gist.github.com/ruiwen/6163115)

Convert to range the initial value from 1 > 16777216 from 0 > 360
Technique here: Convert a number range to another range, maintaining ratio
Then use the HSL colour model, and increment from H0 S100 L100 > H360 S100 L100

Sticking to RGB: Always incrementing by one will not result in a steady grade through the spectrum. For example, when you go from #0000ff (which is blue) to that +1, you end up at #000100, which is essentially black.
Instead, you will probably want to do something more like incrementing each of the three values (the R value, the G value, and the B value) by one. However, that will omit many, many colors. But if smoothness is what you value over comprehensiveness, that's a simple way to get there.
#nada points out that this will give you an awful lot of grey. If you want to avoid that, you can try variations like: increment R until it can't be incremented anymore. Leave it at max value while you increment G until it hits max, then increment B to max. Now reverse it: Decrement R to minimum, then G, then B. This will still miss a ton of colors (in fact, it will miss most colors), but it should be smooth and it should avoid being nothing but grey.
Although this will work (if you don't mind missing most colors), I'm sure there is a better solution. I hope someone weighs in with it. I'm very curious.

You have the hue value, so you need to turn that into the various color formats using fixed brightness and saturation.
To properly scale the hue from [1, 16777215] to a [0, 1] scale, you'll need to do (x - 1) / 16777215. Take this number and feed it into hsl2rgb (here's a JS implementation) with a high lum and relatively high sat.
Something like so:
// From this answer: https://stackoverflow.com/a/9493060/129032
function hslToRgb(h, s, l) {
var r, g, b;
if (s == 0) {
r = g = b = l; // achromatic
} else {
var hue2rgb = function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
function scaleHue(hue) {
return ((hue - 1) / 16777215);
}
var colour = 0;
window.setInterval(function() {
colour = (colour + 100000) % 16777215;
var hue = scaleHue(colour);
var current = hslToRgb(hue, 0.8, 0.8);
$('body').css({
background: '#' + current[0].toString(16) + current[1].toString(16) + current[2].toString(16)
});
}, 50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I increased the step from 1000 to 100000 to make the demo more obvious.

This works for me...
export function intToHex(colorNumber)
{
function toHex(n) {
n = n.toString(16) + '';
return n.length >= 2 ? n : new Array(2 - n.length + 1).join('0') + n;
}
var r = toHex(Math.floor( Math.floor(colorNumber / 256) / 256 ) % 256),
g = toHex(Math.floor( colorNumber / 256 ) % 256),
b = toHex(colorNumber % 256);
return '#' + r + g + b;
}

Generally, this is the formula for converting an integer to rgba
r = (val)&0xFF;
g = (val>>8)&0xFF;
b = (val>>16)&0xFF;
a = (val>>24)&0xFF;
Expressed as javascript
function ToRGBA(val){
var r = (val)&0xFF;
var g = (val>>8)&0xFF;
var b = (val>>16)&0xFF;
var a = (val>>24)&0xFF;
return "rgb(" + r + "," + g + "," + b + ")";
}
Updated fiddle: http://jsfiddle.net/2z82auka/2/

Something like that ?
<script>
function intToHex(colorNumber) {
var R = (colorNumber - (colorNumber%65536)) / 65536;
var G = ((colorNumber - R*65536) - ((colorNumber - R*65536)%256)) / 256;
var B = colorNumber - R*65536 - G*256;
var RGB = R.toString(16) + G.toString(16) + B.toString(16);
return RGB;
}
</script>

Marrying this answer with Drake's:
function colorNumberToHex(colorNumber) {
function toHex(n) {
n = n.toString(16) + '';
return n.length >= 2 ? n : new Array(2 - n.length + 1).join('0') + n;
}
var r = toHex(colorNumber % 256),
g = toHex(Math.floor( colorNumber / 256 ) % 256),
b = toHex(Math.floor( Math.floor(colorNumber / 256) / 256 ) % 256);
return '#' + r + g + b;
}

The picture you've shown suggests you really just want to rotate through a set of continuous colors, not every possible rgb color (since many of them essentially look white or black). I would suggest using HSV as a base instead of RGB. Trying to increment a number that represents an RGB value will lead to the stuttering you see (like #Trott pointed out, going from 0000ff to 000100 jumps from a blue to a black).
Try something like this (Fiddle):
$(document).ready(function(){
var h = 0;
window.setInterval(function(){
h += .01;
if (h >= 1) h-=1;
var rgbColor = HSVtoRGB(h, 1, 1);
var colorString = '#' + convertComponentToHex(rgbColor.r)
+ convertComponentToHex(rgbColor.g)
+ convertComponentToHex(rgbColor.b);
$('body').css({background:colorString});
}, 50);
});
function convertComponentToHex(v) {
return ("00" + v.toString(16)).substr(-2);
}
function HSVtoRGB(h, s, v) {
var r, g, b, i, f, p, q, t;
if (h && s === undefined && v === undefined) {
s = h.s, v = h.v, h = h.h;
}
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return {
r: Math.floor(r * 255),
g: Math.floor(g * 255),
b: Math.floor(b * 255)
};
}
(Thanks to this SO answer for the conversion code. I was too lazy to go figure it out for myself.)

My implementation....
var r = 255;
var g = 0;
var b = 0;
var stage = 1;
var step = 5;
var int = setInterval(function () {
if (stage == 1) {
g += step;
if (g >= 255) {
g = 255;
stage = 2;
}
} else if (stage == 2) {
r -= step;
if (r <= 0) {
r = 0;
stage = 3;
}
} else if (stage == 3) {
b += step;
if (b >= 255) {
b = 255;
stage = 4;
}
} else if (stage == 4) {
g -= step;
if (g <= 0) {
g = 0
stage = 5;
}
} else if (stage == 5) {
r += step;
if (r >= 255) {
r = 255;
stage = 6;
}
} else if (stage == 6) {
b -= step;
if (b <= 0) {
b = 0;
clearInterval(int);
}
}
//console.log(r,g,b);
$('body').css('background-color', 'RGB('+r+','+g+','+b+')');
}, 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Javascript Put 4 integers in the RGBA range

I have a function that puts 4 integers in the RGBA range. In other words, it takes 4 integers, puts the first 3 in the 8-bit range (0-255) (decimal don't matter) and puts the 4th number in the range of 0-1.
And then it makes the fillStyle to that color. (It's important that this all happens in the function because I want to use random Math operations on the numbers)
Here's the code:
function FillColor(r,g,b,a){
if (r > 255){r = 255;}
if (g > 255){g = 255;}
if (b > 255){b = 255;}
if (a > 1){a = 1;}
if (r < 0){r = 0;}
if (g < 0){g = 0;}
if (b < 0){b = 0;}
if (a < 0){a = 0;}
ctx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a + ")";
}
My problem is that it looks unnecessarily long and it mainly just repeats itself. Is there a better way to do this?
Try this:
function FillColor(r, g, b, a) {
for (let i = 0; i < arguments.length; i++) {
if (i === 3) arguments[i] = Math.min(Math.max(parseInt(arguments[i]), 0), 1);
else arguments[i] = Math.min(Math.max(parseInt(arguments[i]), 0), 255);
}
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
}
You can use ternary operator:
r = (r > 255) ? 255 :(r < 0 ) ? 0 : r
example:
<html>
<script type="application/javascript">
function FillCOllor(r) {
r = (r > 255) ? 255 : (r < 0) ? 0 : r
console.log(r)
}
</script>
<body>
<button onclick="FillCOllor(-12)">click</button>
</body>
</html>
// Your code:
/*function FillColor(r,g,b,a){
if (r > 255){r = 255;}
if (g > 255){g = 255;}
if (b > 255){b = 255;}
if (a > 1){a = 1;}
if (r < 0){r = 0;}
if (g < 0){g = 0;}
if (b < 0){b = 0;}
if (a < 0){a = 0;}
ctx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a + ")";
}*/
// Updated function (assuming you can use ES6/ES2015):
function FillColor(r, g, b, a) {
const rgb = (v) => v < 0 ? 0 : v > 255 ? 255 : v;
const alpha = a < 0 ? 0 : a > 1 ? 1 : a;
// You can replace this "return" with your "ctx.fillStyle", but it doesn't work for this example to log the values out.
return `rgba(${rgb(r)}, ${rgb(g)}, ${rgb(b)}, ${a})`;
}
// Updated function (assuming you are bound to ES5):
function FillColorEs5(r, g, b, a) {
var rgb = function(v) {
return v < 0 ? 0 : v > 255 ? 255 : v;
}
var alpha = a < 0 ? 0 : a > 1 ? 1 : a;
// Same thing here...you can replace the "return" with your "ctx.fillStyle" instead.
return "rgba(" + rgb(r) + ", " + rgb(g) + ", " + rgb(b) + ", " + alpha + ")";
}
// Sample running function:
console.log(FillColor(1, 2, 354, 0.1));
console.log(FillColorEs5(1, 2, 354, 0.1));
function FillColor(red,green,blue,alpha){
let [r,g,b] = [red,green,blue].map(c => Math.max(0, Math.min(255, c)));
let a = Math.max(0, Math.min(1, alpha));
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
}

Integrating Old Javascript Functions into React-Native

I'm currently using this package of Javascript on my website. And I need to be able to use it in the app that I'm trying to build (I'm VERY new to react-native--a PHP, javascript developer here).
How do I integrate it? Do I have to convert it or is it possible to just include it and call the functions? I have no idea. Sigh. I've searched but I didn't find anything that answered my question--though that could be because I'm new to RN and don't know what the heck I'm doing :(.
Thanks in advance for your advice!
To use the functions, I currently just call them with the second line in Javascript:
var strINeedHashed = "Hash Me Please";
var hash = hex_sha256(strINeedHashed);
Here's the JS I need access to:
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
function safe_add (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function S (X, n) {return ( X >>> n ) | (X << (32 - n));}
function R (X, n) {return ( X >>> n );}
function Ch(x, y, z) {return ((x & y) ^ ((~x) & z));}
function Maj(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));}
function Sigma0256(x) {return (S(x, 2) ^ S(x, 13) ^ S(x, 22));}
function Sigma1256(x) {return (S(x, 6) ^ S(x, 11) ^ S(x, 25));}
function Gamma0256(x) {return (S(x, 7) ^ S(x, 18) ^ R(x, 3));}
function Gamma1256(x) {return (S(x, 17) ^ S(x, 19) ^ R(x, 10));}
function core_sha256 (m, l) {
var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2);
var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);
var W = new Array(64);
var a, b, c, d, e, f, g, h, i, j;
var T1, T2;
/* append padding */
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >> 9) << 4) + 15] = l;
for ( var i = 0; i<m.length; i+=16 ) {
a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
for ( var j = 0; j<64; j++) {
if (j < 16) W[j] = m[j + i];
else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
T2 = safe_add(Sigma0256(a), Maj(a, b, c));
h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2);
}
HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]); HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]);
}
return HASH;
}
function str2binb (str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
return bin;
}
function binb2hex (binarray) {
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for (var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
}
return str;
}
function hex_sha256(s){return binb2hex(core_sha256(str2binb(s),s.length * chrsz));}
if that is working javascript, you just add it to your project's code.
Fastest, a bit ugly way, is to include that code in the file where you using it. More proper way would be to make of file for that and include es6 exports for functions that you need to access.
React Native uses JavaScript, so in theory if you function is written in JavaScript you should have no issues integrating it into your React Native project. Just simply add your old function to the React Native project and just call it as you normally would :)

Generating the same SHA1 UUID in golang and Javascript

I have what I thought was a pretty simply question. I'm using this code to generate a SHA1 uuid in Golang:
namespace := uuid.Parse("b9cfdb9d-f741-4e1f-89ae-fac6b2a5d740")
sha := uuid.NewSHA1(namespace, []byte("something"))
fmt.Println(sha.String())
Now I want to generate the same UUID in javascript, and I thought it would be as easy as something like this:
var hash = CryptoJS.SHA1("b9cfdb9d-f741-4e1f-89ae-fac6b2a5d740" + "something")
// chomp the hash into a UUID string
However, I'm running into serious issues. It seems that the uuid.Parse function in Golang is running this parsing function that converts the namespace to a 16-byte array, so even though I use the same SHA1 algorithm in Javascript, I'm not getting the same output.
I'v been messing around with doing the same in JS, but I'm stumped.
Any smart crypto people in here that can help me?
Well, that only took me a month.
var SHA1Generator = {
hex_chr: "0123456789abcdef",
hex: function (num) {
var str = "";
for (var j = 7; j >= 0; j--)
str += this.hex_chr.charAt((num >> (j * 4)) & 0x0F);
return str;
},
str2blks_SHA1: function (str) {
var nblk = ((str.length + 8) >> 6) + 1;
var blks = new Array(nblk * 16);
for (var i = 0; i < nblk * 16; i++) blks[i] = 0;
for (i = 0; i < str.length; i++)
blks[i >> 2] |= str.charCodeAt(i) << (24 - (i % 4) * 8);
blks[i >> 2] |= 0x80 << (24 - (i % 4) * 8);
blks[nblk * 16 - 1] = str.length * 8;
return blks;
},
add: function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
},
rol: function (num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
},
ft: function (t, b, c, d) {
if (t < 20) return (b & c) | ((~b) & d);
if (t < 40) return b ^ c ^ d;
if (t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
},
kt: function (t) {
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
},
calcSHA1FromByte: function(byteArr) {
var str = '';
for(var i=0; i<byteArr.length; i++)
str += String.fromCharCode(byteArr[i]);
return this.calcSHA1(str);
},
calcSHA1: function (str) {
if (str != '') {
var x = this.str2blks_SHA1(str);
var w = new Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = x[i + j];
else w[j] = this.rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
t = this.add(this.add(this.rol(a, 5), this.ft(j, b, c, d)), this.add(this.add(e, w[j]), this.kt(j)));
e = d;
d = c;
c = this.rol(b, 30);
b = a;
a = t;
}
a = this.add(a, olda);
b = this.add(b, oldb);
c = this.add(c, oldc);
d = this.add(d, oldd);
e = this.add(e, olde);
}
return this.hex(a) + this.hex(b) + this.hex(c) + this.hex(d) + this.hex(e);
}
else {
return '';
}
}
};
function stringToByteArray(str) {
var bytes = [];
for (var i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
return bytes;
}
function uuidToByteArray(hex) {
// If this is a uuid, remove the dashes
hex = hex.replace(/-/g, "");
// convert each hex number into a string representation
// of the byte integer.
var bytes = [];
for(var i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.substring(i, i+2),16));
}
return bytes;
}
function sha1ToUUID5(hash) {
var uuid = hash.substring(0, 8) +
'-' + hash.substring(8, 12) +
// four most significant bits holds version number 5
'-' + ((parseInt(hash.substring(12, 16), 16) & 0x0fff) | 0x5000).toString(16) +
// two most significant bits holds zero and one for variant DCE1.1
'-' + ((parseInt(hash.substring(16, 20), 16) & 0x3fff) | 0x8000).toString(16) +
'-' + hash.substring(20, 32); //12 digits
return uuid;
}
var namespace = "e75a36a9-3323-40dd-a7d1-1c57ad2aa3cd"
var id = "event154"
var namespaceBytes = uuidToByteArray(namespace);
var idBytes = stringToByteArray(id);
var allBytes = namespaceBytes.concat(idBytes);
console.log("ORG 4505612c-c323-5d6f-b5cc-b7f362b9ba55")
console.log("NEW " + sha1ToUUID5(SHA1Generator.calcSHA1FromByte(allBytes)))

What was used to compress this code? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to understand what's going on in this code: http://js1k.com/2013-spring/demo/1396
This doesn't look like it's been minified or encoded in Base62 to me. When I paste it in Vim weird characters appear everywhere. Is there a way I can decode it?
This has been produced using the Data URI Scheme
https://en.wikipedia.org/wiki/Data_URI_scheme
The javascript file has been supplied as a URI which contains the file's contents. Lots of codes have been URL escaped, hence all the \s. And it may have been minified before that.
The data here is a whole HTML document. The first part is the start of the HTML file:
javascript:
'<!doctype html>\n<html>\n\t<head>\n\t\t<title>JS1k, 1k demo submission [1396]</title>\n\t\t<meta charset="utf-8" />\n\t</head>\n\t<body>\n\t\t<canvas id="c"></canvas>\n\t\t
After that an inline script:
var b = document.body;\n\t\t\tvar c = document.getElementsByTagName(\'canvas\')[0];\n\t\t\tvar a = c.getContext(\'2d\');\n\t\t\tdocument.body.clientWidth; // fix bug in webkit: http://qfox.nl/weblog/218\n\t\t
which you can easily decode as:
var b = document.body;
var c = document.getElementsByTagName('canvas')[0];
var a = c.getContext('2d');
document.body.clientWidth; // fix bug in webkit: http://qfox.nl/weblog/218
etc etc.
End of code there is script, which is used to decode code
for (Y = 0; $ = 'zxqj`_^ZWVUQONMKJIHGCA#8$ ' [Y++];)
with(_.split($)) _ = join(pop());
eval(_)
I put this firebug ... instead of eval(_) put console.log( _ )
code is
e = null;
T = function (b) {
c.width = c.height = 19 * s;
a.fillStyle = "#DB5";
a.fillRect(0, 0, c.width, c.width);
for (i = s / 2; i < c.width; i += s) a.moveTo(i, s / 2), a.lineTo(i, c.width - s / 2), a.moveTo(s / 2, i), a.lineTo(c.width - s / 2, i);
a.stroke();
b && (f = 19 * ~~(0.5 + (b.clientY - s / 2) / s) + ~~(0.5 + (b.clientX - s / 2) / s), t[f] == e && (t[f] = d, (L(f) | !(L(f + 1) & L(f - 1) & L(f + 19) & L(f - 19))) & (!m | f != n) ? "d" == b.type[5] ? (m = 0, u = f, d = !d, E(f + 1, d), E(f - 1, d), E(f + 19, d), E(f - 19, d), E(f)) : (t[f] = e, a.beginPath(), a.arc(~~(0.5 + (b.clientX - s / 2) / s) * s + s / 2, ~~ (0.5 + (b.clientY - s / 2) / s) * s + s / 2, s / 2 - 1, 0, 6.3, 1), a.strokeStyle = a.fillStyle = "rgba(0,0,0,0.3)", d && (a.fillStyle = "rgba(255,255,255,0.3)"), a.fill(), a.stroke()) : t[f] = e));
a.strokeStyle = "#000";
a.fillStyle = "#000";
for (i = s / 2 + 75; i < c.width; i += 6 * s) for (h = s / 2 + 75; h < c.width; h += 6 * s) a.beginPath(), a.arc(i, h, 2, 0, 6.3, 1), a.fill();
m && (t[n] = d, L(u) || (a.beginPath(), a.rect(n % 19 * s + s / 2 / 2, ~~ (n / 19) * s + s / 2 / 2, s / 2, s / 2), a.stroke()), t[n] = e);
for (i = t.length; i--;) t[i] != e && (a.beginPath(), a.arc(i % 19 * s + s / 2, ~~ (i / 19) * s + s / 2, s / 2 - 1, 0, 6.3, 1), a.fillStyle = "#000", t[i] && (a.fillStyle = "#FFF"), a.fill(), a.stroke())
};
E = function (b, g) {
if (!L(b, g)) {
1 == w.length && (m = 1, n = b);
for (i = w.length; i--;) t[w[i]] = e
}
};
L = function (b, g) {
w = [];
g == e && (g = t[b]);
l = function (b) {
for (i = w.length; i--;) if (w[i] == b) return;
w.push(b);
0 != (b + 1) % 19 && t[b + 1] == g && l(b + 1);
0 != b % 19 && t[b - 1] == g && l(b - 1);
t[b + 19] == g && l(b + 19);
t[b - 19] == g && l(b - 19)
};
if (g != e && g == t[b]) l(b);
else return 1;
for (i = w.length; i--;) if (0 != (w[i] + 1) % 19 && t[w[i] + 1] == e || 0 != w[i] % 19 && t[w[i] - 1] == e || 342 > w[i] && t[w[i] + 19] == e || 19 <= w[i] && t[w[i] - 19] == e) return 1;
return 0
};
s = 25;
d = m = n = 0;
c.addEventListener("mousemove", T);
c.addEventListener("mousedown", T);
t = [];
T();

Convert integer to alpha ordered list equivalent

I need to a function to convert an integer to the equivalent alpha ordered list index. For example:
1 = a
2 = b
.
.
.
26 = z
27 = aa
28 = ab
.
.
etc.
Currently I have the following which almost works but there's a small logic error somewhere that makes it not quite get it right (it goes ax, ay, bz, ba, bb, bc...):
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = '',
place,
num,
i;
for ( i = 0; Math.pow(alphaMax, i) < int; i++ ) {
place = Math.pow(alphaMax, i);
num = Math.floor( ( int / place ) % alphaMax);
asciiCode = ( num == 0 ? alphaMax : num ) + asciiStart - 1;
char = String.fromCharCode(asciiCode);
alpha = char + alpha;
}
return alpha;
}
for (i = 1; i < 300; i++) {
console.log( i + ': ' + intToAlpha(i) );
}
This function is used in NVu/Kompozer/SeaMonkey Composer, with a small tweak to generate lower case directly:
function ConvertArabicToLetters(num)
{
var letters = "";
while (num > 0) {
num--;
letters = String.fromCharCode(97 + (num % 26)) + letters;
num = Math.floor(num / 26);
}
return letters;
}
You need to make sure that you use the correct value when taking the mod.
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = "";
while(int > 0) {
char = String.fromCharCode(asciiStart + ((int-1) % alphaMax));
alpha = char + alpha;
int = Math.floor((int-1)/26);
}
return alpha;
}
A while back I needed the same thing in SQL, so I asked (and answered) the question Multi-base conversion - using all combinations for URL shortener.
The thing that is making it complicated is that it's not a straight base conversion, as there is no character representing the zero digit.
I converted the SQL function into Javascript:
function tinyEncode(id) {
var code, value, adder;
var chars = 'abcdefghijklmnopqrstuvwxyz';
if (id <= chars.length) {
code = chars.substr(id - 1, 1);
} else {
id--;
value = chars.length;
adder = 0;
while (id >= value * (chars.length + 1) + adder) {
adder += value;
value *= chars.length;
}
code = chars.substr(Math.floor((id - adder) / value) - 1, 1);
id = (id - adder) % value;
while (value > 1) {
value = Math.floor(value / chars.length);
code += chars.substr(Math.floor(id / value), 1);
id = id % value;
}
}
return code;
}
Demo: http://jsfiddle.net/Guffa/mstBe/

Categories