关于前端:consolelog图片彩蛋

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

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%)");

图片彩蛋

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

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 会显示空白 :

思考到兼容性问题,能够采纳 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 以下。

参考

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

How to display images in the JavaScript console of the Browser

consoleimg

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理