2016-05-23 72 views

回答

1

有一個技巧,可以輕鬆地從任何CSS格式轉換爲十六進制:使用虛擬context2d,設置它的fillStyle,然後再讀一遍:它現在是十六進制! :

function convertToHex(nonHexColorString) { 
    var ctx = document.createElement('canvas').getContext('2d'); 
    ctx.fillStyle = nonHexColorString; 
    return ctx.fillStyle; 
} 

console.log(convertToHex('rgb(0,0,0)'); // -->> output is #000000 

緩存context2d如果速度事項:

function convertToHex(nonHexColorString) { 
    var ctx = convertToHex.dummyContext2d; 
    if (!ctx) { 
     ctx = convertToHex.dummyContext2d = document.createElement('canvas').getContext('2d'); 
    } 
    ctx.fillStyle = nonHexColorString; 
    return ctx.fillStyle; 
} 
相關問題