Snippet for RGB to Hex

Started by G_G, October 25, 2015, 01:30:09 am

Previous topic - Next topic

G_G

October 25, 2015, 01:30:09 am Last Edit: October 25, 2015, 01:59:14 am by gameus
Since MV now uses Hex values for colors, here's a snippet that can convert RGB to Hex. Makes things friendlier for devs and end users.

function toHex(n) {
   n = parseInt(n,10);
   if (isNaN(n)) return "00";
   n = Math.max(0,Math.min(n,255));
   return "0123456789ABCDEF".charAt((n-n%16)/16)
       + "0123456789ABCDEF".charAt(n%16);
};

function rgbToHex(rgb) {
   nrgb = rgb.replace(/\s+/g, '');
   nrgb = nrgb.split(',');
   return ("#" + toHex(nrgb[0]) + toHex(nrgb[1]) + toHex(nrgb[2]));
};


Usage:
var rgb_value = "255, 0, 255"; // Uses string format for plugin properties
var hex_value = rgbToHex(rgb_value) // Outputs #FF00FF


EDIT: Gonna leave this here for people to look at but I realized that you don't have to use Hex in MV. It just requires css formatted colors. Which could be hex or could be "rgb( r, g, b )". Also a function that already exists in the engine "rgbToCssColor( r, g, b )".