我們在使用腳手架的時候,經常會看到終端輸出五顏六色的字符,看起來很酷,如果我們想實作這種效果,通常都會用colors或者chalk來快速實作,
那么問題來了,他們是如何實作的呢?
const predefineColor = [196, 214, 46, 53, 205, 196] const out = 'Double Raindows All Day Long' /** * ESCAPE (U+001B) unicode表示法即 `u001b` */ /** * 8位顏色表示法 n的色值是預定義的,可通過 https://zh.wikipedia.org/wiki/ANSI轉義序列 查表得到 * ESC[38;5;<n>m 選擇前景色,其中`38`表示前景色,`n`表示預定義的256種顏色的色值 * ESC[48;5;<n>m 選擇背景色,其中`48`表示背景色,`n`表示預定義的256種顏色的色值 */ console.log('\u001b[38;5;214mFirst some yellow text'); /** * 3/4位顏色表示法 n的色值是預定義的,可通過 https://zh.wikipedia.org/wiki/ANSI轉義序列 查表得到 * ESC[<n>m 選擇前景色 其中n取值范圍30<=n<=37 * ESC[<n>m 選擇前景色 其中n取值范圍40<=n<=47 */ console.log('\u001b[92m\u001b[4mUnderline that text\u001b[0m'); /** * 24位顏色表示法, 支持rgb色值,n的色值是預定義的,可通過 https://zh.wikipedia.org/wiki/ANSI轉義序列 查表得到 * ESC[38;2;<R>;<G>;<B>m 選擇前景色,其中`38`表示前景色,`RGB`表示三原色,n取值范圍0<=n<=255 * ESC[48;2;<R>;<G>;<B>m 選擇背景色,其中`48`表示背景色,`RGB`表示三原色,n取值范圍0<=n<=255 */ console.log('\u001b[38;2;250;0;0m\u001b[1mMake it bold and red\u001b[0m'); console.log('\u001b[31m\u001b[3mItatic that text\u001b[0m'); console.log('\u001b[37m\u001b[42mBackground color attack!\u001b[0m'); function print(out) { const res = out.split(' ') let str = ''; res.forEach(i => { [].forEach.call(i, (j, index) => { str += `\u001b[38;5;${predefineColor[index % predefineColor.length]}m${j}` }) str += " " }) console.log(str); } print(out)




參考資料:
ANSI轉義序列
Unicode字串列
控制臺ANSI Color的表示和用法
關于\u001b轉義字符
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457057.html
標籤:JavaScript
上一篇:如何利用js來制作時間倒計時效果
