我知道标题很奇怪,但是如果你读了这个,你就会明白我的意思了。
所以,这是我的代码:
const colors = {
Red: 0xff0000,
Orange: 0xffa500,
Yellow: 0xffff00,
Green: 0x008000,
Blue: 0x0000ff,
Indigo: 0x4b0082,
Violet: 0xee82ee,
Purple: 0x8c03fc
}
function ColorNameError(prefix, ...message) {
Error.call(this);
this.message = `[${prefix}]: ${message.join(" ")}`;
this.name = "ColorNameError";
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ColorNameError);
}
}
ColorNameError.prototype = Object.create(Error.prototype);
function colorNames(colors) {
if (typeof colors === "undefined") {
throw new ColorNameError("NoObjectProvided", "No colors object provided.");
}
if (typeof colors !== "object") {
throw new ColorNameError(
"TypeError",
`
Expected colors to be an "object" but got "${typeof colors}" instead.`
);
}
var colorNames = Object.keys(colors);
var formattedColors = "";
var responseTime = new Date();
for (var i = 0; i < colorNames.length; i++) {
var colorName = colorNames[i];
var colorValue = colors[colorName];
var ansiColor = hexToAnsi(colorValue);
formattedColors += `\x1b[1m${colorName}\x1b[0m ${ansiColor}${ansiColor}\n`;
}
var totalColors = colorNames.length;
var elapsedTime = new Date() - responseTime;
formattedColors += `\u001b[1mTotal Colors: \u001b[36m${totalColors}\u001b[0m\n\u001b[1mResponse Time: \u001b[33m${elapsedTime}ms\u001b[0m`;
return formattedColors;
}
/**
*
* @param {HexValueInput} hexValue
* @returns {ansiCode} ansiCode
*/
function hexToAnsi(hexValue) {
var hexString = hexValue.toString(16).padStart(6, "0");
var r = parseInt(hexString.substring(0, 2), 16);
var g = parseInt(hexString.substring(2, 4), 16);
var b = parseInt(hexString.substring(4, 6), 16);
var ansiColorCode =
16 +
36 * Math.round((r / 255) * 5) +
6 * Math.round((g / 255) * 5) +
Math.round((b / 255) * 5);
return `\u001b[38;5;${ansiColorCode}m`;
}
它应该从颜色对象中记录颜色名称,颜色应该是颜色名称的值,就像对象中的红色键应该是红色,因为它的值是红色十六进制。但是它不是红色,而是像没有颜色一样无色,但扭曲的是,下一个颜色橙色是红色!喜欢看截图
我相信问题在于这行代码。
formattedColors += `\x1b[1m${colorName}\x1b[0m ${ansiColor}${ansiColor}\n`;
${ansiColor}
代表改变颜色的转义序列
这个
\x1b[1m
代表要格式化的文字亮
这个
\x1b[0m
表示重置(以便在下一次迭代中设置新颜色)
你做错的是你必须在实际文本之前应用转义序列。您的序列提前了一次迭代,因为您在最后应用了
${ansiColor}
。
我认为这应该可以解决问题,改变这条线
formattedColors += `\x1b[1m${ansiColor}${colorName}\x1b[0m\n`; //bright + colorEscape + colorName + reset
参考这篇文章:How to change node.js's console font color?
希望对您有所帮助!