JavaScript: Převod barevných složek RGB do tvaru RRGGBB

Při tvorbě jakékoli aplikace je dobré vyvažovat přehlednost zápisu kódu s jeho efektivitou. Protože interprety JavaScriptu bohužel nejsou z nejrychlejších, přichází velmi často ke slovu právě faktor druhý, na úkor intuitivnosti zápisu. Jako třeba u následujícího problému:

Máme barevné složky R, G a B, z nichž každá je vyjádÅ™ena desetinným číslem v intervalu <0; 1>. Z tÄ›ch potÅ™ebujeme získat Å™etÄ›zec ve tvaru RRGGBB. Složky bude tedy tÅ™eba zvÄ›tÅ¡it do rozsahu 0–255, zaokrouhlit, pÅ™evést na čísla Å¡estnáctková a jednoznakové výsledky zleva doplnit nulou, aby sestavený Å™etÄ›zec mÄ›l vždy právÄ› Å¡est znaků. Jak ale splnit poslední požadavek co nejrychleji a bez podmínÄ›ného pÅ™idávání nuly?

Metoda číslo.toString(16) sice převede číslo do šestnáctkové soustavy, ale k doplnění počáteční nuly ji přimět nelze. Na sprintf() můžeme zapomenout a co se týče regulárních výrazů, jejich vyhodnocení je pomalé. Nabízí se vkládat nulu vždy a potom z řetězce zprava vytáhnout dva znaky, tedy ('0'+cislo).substr(-2), jenže IE záporný offset nepodporuje.

Nedávno mě trklo zajímavé řešení. K číslům nejprve přičteme 256, čímž po převodu získáme vždy nejméně 10016 a nejvíce 1FF16. Pak zbývá jen oříznout počáteční jedničku. Jak jsem zmínil na začátku, přehlednost takového algoritmu je na pováženou, ale za tu efektivitu jistě stojí:

function rgbToHex(R, G, B) {
    return (
        Math.round(256 + 255*R).toString(16).substr(1) +
        Math.round(256 + 255*G).toString(16).substr(1) +
        Math.round(256 + 255*B).toString(16).substr(1)
    )
}

Komentáře

[1] Karel [web] – 2008-07-21, 10.42

Dobrý článek, slyším o této možnosti poprvé.

[2] Jiří Počta [web] – 2008-08-04, 11.27

Prostě paráda :-D opět se ti něco povedlo :-) ...

[3] vmaglhbbdp [web] – 2011-05-28, 17.52

[4] Jordan 3 – 2012-01-10, 9.18

Alice is designed to make the former more easily when walking, http://www.onlineshoesbar.com/air-jordan-3-c-3.html Jordan 3 unique ventilation design is a comfortable casual shoes. http://www.onlineshoesbar.com/jordan-evolution-85-c-28.html Jordan Evolution 85 In 1972 the first non-air basketball shoes, classic replica, using a high-quality leather, accompanied by visible heel air cushion, the appearance of the popular running shoes for customers with sporty design. Fun colors to attract a lot of sun and handsome boy. http://www.onlineshoesbar.com/jordan-flight-45-c-29.html Jordan Flight 45 Provide flexibility and breathability, designed specifically for women. http://www.onlineshoesbar.com/jordan-prime-5-c-30.html Jordan Prime 5 Incorporation of material inside the rubber increased durability, are a professional sports shoes.

[5] cheap jordans [web] – 2012-01-12, 4.25

the appearance of <a href="http://www.nikeshoebar.com/nike-air-jordan-10-retro-black-p-292.html">Nike Air Jordan Retro XXI black gold</a> is very stout, but with a color of black gold to make it look very shocked, giving a domineering feeling. <a href="http://www.nikeshoebar.com/nike-air-jordan-10-retro-black-white-p-291.html">Cheap Nike Air Jordan Retro</a> is relatively wide and large, suitable for wide feet people, the shoes with IPS+ hind palm <a href="http://www.nikeshoebar.com/nike-air-jordan-10-white-p-289.html">Nike Air Jordan 10 Black White</a> interchangeable technology, that can increase the cushioning ability, and also widened the crowd scope, while the wide and large carbon plate is enough to explain AJ21's position in NIKE, it's absolutely the star high-end shoes. and all these are in jordanstopsales.com, where you can get <a href="http://www.nikeshoebar.com/nike-air-jordan-10-white-01-p-290.html">cheap jordan shoes</a>.

[6] dior bag [web] – 2012-01-12, 6.27


<a href="http://www.diorbag4u.com/h4fendi-bagsh4-c-32.html?page=3&sort=20a">Fendi White Blue Orange Ladies Handbags</a>In some cases, bags can also help them to ease the inner tension and anxiety package to reflect the quality of life and feminineWith all of the jewelry, handbags, should be the most important with a single product, not only is in fact with effects, and more beautiful appearance is also very important,<a href="http://www.diorbag4u.com/fendi-white-gold-ladies-handbag-p-786.html">Fendi White Gold Ladies Handbag</a>a practical and personalized handbag can not only improve the overall mix of highlights and more make more overall grade wave of burst-digit year will once again struck, a gorgeous big handbag is definitely a symbol of fashion, with aristocratic style or simple design with a strong luxury atmosphere A la carte with a handbag everywhere carefully reveals their pursuit of quality of life Beautiful network Xiaobian we recommend several handbag bag, clever take the most beautiful dress to wear clothing with you, let you hold live scene, metal clasp purse, never disappointing,<a href="http://www.diorbag4u.com/fendi-white-ladies-handbags-p-789.html">Fendi White Ladies Handbags</a>the quilting process with complex color pattern light overall fashion sense, but there were many well-designed during the detail, bright colors and pockets with enough functional classification, and travel to meet the daily admission each year with the enduring classic style, the more classic style of the past, the more hot, Europe love is the region with the endless number of supermodel, fashion people is to be interpreted as the trend of choice, the handle can be portable, so that match your travel more convenient choice

Přidat komentář

Identifikace autora

(zobrazí se v antispam podobě)

Komentář

Nepoužívej HTML značky a piš pokud možno s diakritikou. Na ostatní komentáře se odkazuj např. [1]

Díky za tvůj názor!

Navigace

Hledání