开发者

Converting integers to hex string in JavaScript

How do I convert integer byte values of red, green and blue to a hex string, which can then be assigned to a context for rendering onto a HTML5 canvas?

For example, convert cyan,

var r = 0;
var g = 255;
var b = 255;

To a hex string fo开发者_如何学运维r assigning to a context fill colour.

this.context.fillStyle = '#00FFFF';

Or is there a better way to do this altogether?


To convert a number to hex, you can use the built-in toString(16) function. Simple code:

function convert(integer) {
    var str = Number(integer).toString(16);
    return str.length == 1 ? "0" + str : str;
};

function to_rgb(r, g, b) { return "#" + convert(r) + convert(g) + convert(b); }

var color = to_rgb(r, g, b);


Just use the RGB values, like:

this.context.fillStyle = "rgb(0,255,255)";


I think, the simplest way is:

var g = 255;
g.toString(16); //gives "ff"

Use the feature that gives language.


Convert one integer to a hex byte like:

const g = 255;

gPadded = Number(g).toString(16).padStart(2, "0");

This gets nicer with an array:

const r = 0;
const g = 255;
const b = 255;
const color = [r, g, b];

this.context.fillStyle = "#" + color.map(i=>i.toString(16).padStart(2, "0")).join("");


function pad(number, length) {
    var str = '' + number;
    while (str.length < length) str = '0' + str;
    return str;
}

function toRGBHex(r,g,b) { 
    return pad(r.toString(16),2) + pad(g.toString(16),2) + pad(b.toString(16),2); 
}


To convert your individual RGB values into a hex color, you can use this function, although it makes more sense just to use "rgb("+r+","+g+","+b+")" instead.

function rgbToHex(r,g,b) {
    return "#"+("00000"+(r<<16|g<<8|b).toString(16)).slice(-6);
}


You can use .toString(16)

let decimalNumber = 255;
decimalNumber.toString(16)
// Expected output is "FF"

or if you want to convert binary radix

let decimalNumber = 24;
decimalNumber.toString(2)
// Expected output is "1010"

source MDN .toString(16)


You can write your own method for this conversion -

// function to generate the hex code
function getHex(dec)
{
    var hexArray = new Array( "0", "1", "2", "3", 
                              "4", "5", "6", "7",
                              "8", "9", "A", "B", 
                              "C", "D", "E", "F" );

    var code1 = Math.floor(dec / 16);
    var code2 = dec - code1 * 16;

    var decToHex = hexArray[code2];

    return (decToHex);
} 

original source - http://programming.top54u.com/post/Javascript-Convert-Decimal-to-Hex.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜