【Javascript】利用console.log()占位符功能实现日志美化
console.log() 不仅接受任何类型的参数,包括字符串、数字、布尔值、对象、数组、函数等。最厉害的是,它支持占位符!
常用的占位符:
%s
- 字符串%d
or%i
- 整数%f
- 浮点数%o
- 对象%c
- CSS 样式
代码:
function _isEmpty(value) {
return value == null || value === undefined || value === '';
};
function _prettyText(title, content, color) {
console.log(
`%c ${title} %c ${content} %c`,
`background:${color};border:1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`,
`border:1px solid ${color}; padding: 1px; border-radius: 0 2px 2px 0; color: ${color};`,
'background:transparent'
);
}
/**
* 输出信息级别的日志
* @param {String} content 内容
* @param {String} title 标题
*/
function info(content, title = '') {
title = _isEmpty(title) ? 'Info' : title;
_prettyText(title, content, '#909399');
}
/**
* 输出警告级别的日志
* @param {String} content 内容
* @param {String} title 标题
*/
function warning(content, title = '') {
title = _isEmpty(title) ? 'Warning' : title;
_prettyText(title, content, '#E6A23C');
}
/**
* 输出错误级别的日志
* @param {String} content 内容
* @param {String} title 标题
*/
function error(content, title = '') {
title = _isEmpty(title) ? 'Error' : title;
_prettyText(title, content, '#F56C6C');
}
/**
* 输出成功级别的日志
* @param {String} content 内容
* @param {String} title 标题
*/
function success(content, title = '') {
title = _isEmpty(title) ? 'Success' : title;
_prettyText(title, content, '#67C23A');
}
function picture(url, scale = 1) {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
const c = document.createElement('canvas');
const ctx = c.getContext('2d');
if (ctx) {
c.width = img.width;
c.height = img.height;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(img, 0, 0);
const data_url = c.toDataURL('image/png');
console.log(
`%c `,
`font-size: 1px;
padding: ${Math.floor((img.height * scale) / 2)}px ${Math.floor((img.width * scale) / 2)}px;
background-image: url(${data_url});
background-repeat: no-repeat;
background-size: ${img.width * scale}px ${img.height * scale}px;
color: transparent;
`
);
}
};
img.src = url;
}
export {
info,
error,
warning,
success,
picture,
}