likes
comments
collection
share

console.log图片彩蛋

作者站长头像
站长
· 阅读数 9

近期接到了一个需求,把文案和图片藏在网页代码中,作为一个有趣的小彩蛋,实践过程中发现有不少坑,跟大家分享下 ₍ᐢ..ᐢ₎♡ ˗ˋˏ♡ˎˊ˗

console.log图片彩蛋

console.log

console.log() 方法向 Web 控制台输出一条信息,在传递给 console 的方法的时候使用下面的字符以期进行参数的替换。

格式占位符作用
%s字符串
%d 或 %i整数
%f浮点数
%o可展开的DOM
%O列出DOM的属性
%c根据提供的css样式格式化字符串

而彩蛋的实现可以使用 %c 为打印内容定义样式,指令前的文本不会受到影响,但指令后的文本将会使用参数中声明的 CSS 样式。

console.log("控制台 %c小彩蛋", "font-size: 20px; color: #fff; border-radius: 5px; padding: 10px 25px;background: linear-gradient(315deg, #cdb4db 0%, #ffafcc 50%, #a2d2ff 100%)");

console.log图片彩蛋

图片彩蛋

打印图片 🖼️ 的实现思路如下:

1、背景图像

由于只能定义样式,所以 console 不支持 <img> 标签,只支持使用 background-image 来设置背景图。⚠️ 需要注意的是,设置背景图需要带有文本内容,不然是不生效的,因此在 %c 后面留有一个空白字符是必要的:

var style = [
  `background: url(${url}) center center no-repeat`,
].join(' ');
console.log("%c ", style);

2、尺寸大小

  • 由于不支持设置 widthheight,需要使用 paddingline-height 来代替宽高;

  • font-size 需要设置为0,让字体不占用空间,否则空白字符也会撑出空间;

  • padding 不可缺少,否则只靠 line-height 高度虽然撑起来了但是会显示空白;

  • chrome 浏览器不能设置 line-height,否则高度是图片高度的 2倍;

  • chrome 浏览器 需要设置 line-height,否则高度只靠 padding 撑不起来。

'font-size: 0px;',
!isChromium ? `line-height: ${this.height}px;` : '',
`padding: ${this.height / 2}px ${this.width / 2}px;`,

3、base64

另外,部分浏览器不支持网络图片路径,(即 background: url('https://xxx.png') ),比如 chrome 会显示空白 :

console.log图片彩蛋

考虑到兼容性问题,可以采用 base64 的方式。但是如果图片较大,或者色彩比较丰富,那么其 base64 编码后的字符串会非常大,可以通过 fetch 请求实时地将图片转成 base64:

async function getBase64FromUrl (url) {
    const data = await fetch(url);
    const blob = await data.blob();
    return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onloadend = () => {
            const base64data = reader.result;
            resolve(base64data);
        }
        reader.onerror = reject;
    });
}

4、扩展 console

最后扩展 console 对象,添加 image 方法

console.image = function(url) {
  const image = new Image();
  image.onload = function () {
    var isChromium = navigator.userAgent.match(/chrome|chromium|crios/i) && !!window.chrome;
  var style = [
    'font-size: 0px;',
    !isChromium ? `line-height: ${this.height}px;` : '',
    `padding: ${this.height / 2}px ${this.width / 2}px;`,
    `background: url(${url}) center center no-repeat;`,
    'background-size: contain;',
  ].join(' ');
  console.log('%c ', style);
  };
  image.src = url;
};

getBase64FromUrl(imgUrl).then(console.image);

⚠️ 注意

有一点要提醒大家,Firefox 只支持 8kb 大小的图片资源,一旦超过这个数量就会显示空白。如果需要兼容火狐的,建议把图片压缩至 8kb 以下。

console.log图片彩蛋

参考

Log images to the DevTools Console with console.image()

How to display images in the JavaScript console of the Browser

consoleimg