简体   繁体   中英

How can I get rgb (or hex) code from css color-name in javascript?

I am making a canvas gauge plugin and I need to convert css color codes like 'pink' and 'orange' into RGB format.

I thought of setting some element to background: pink; and the getting that color back with $('el').css('background');like this but I don't know if that would always return what i want and it seems weird anyway.

I am hoping there is some built in window method or something that can do this conversion for me without me having to include a big map-object for all the codes.

github.com/jquery/jquery-color/blob/master/jquery.color.js

可能是您所追求的处理库。

I need to convert css color codes like 'pink' and 'orange' into RGB format [...] I am hoping there is some built in window method or something that can do this conversion for me without me having to include a big map-object for all the codes.

Yes, there is. The method you are looking for is window.getComputedStyle()

You can run through the following steps:

  • create a standard <div>
  • add the color to the style object of the <div>
  • append the <div> to the DOM
  • use window.getComputedStyle() to inspect the computed styles of the <div>

Working Example:

 const colorKeywordToRGB = (colorKeyword) => { // CREATE TEMPORARY ELEMENT let el = document.createElement('div'); // APPLY COLOR TO TEMPORARY ELEMENT el.style.color = colorKeyword; // APPEND TEMPORARY ELEMENT document.body.appendChild(el); // RESOLVE COLOR AS RGB() VALUE let rgbValue = window.getComputedStyle(el).color; // REMOVE TEMPORARY ELEMENT document.body.removeChild(el); return rgbValue; } console.log('pink:', colorKeywordToRGB('pink')); console.log('orange:', colorKeywordToRGB('orange'));


Further Reading:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM