JS 实现浏览器控制台打印图片 console.image()


平时调试的时候,我门会使用 console.log 等方式查看数据。但对于图片来说,仅靠展示的数据与结构,是无法想象出图片最终呈现的样子的。

我们可以把图片数据通过 img 标签展示到页面上,或将图片下载下来进行预览。但这样的调试过程实在是复杂,何不实现一个 console.image() 呢?

实现 console.image():

参考 github 上已实现的库 github.com/adriancooney/console.image Star 1.7k(本文发布前)。 实现代码如下:

(function(console) {
    // 控制台不支持 background-repeat:no-repeat,作者使用 padding 的方式来限制显示区域。
    function getBox(width, height) {
        return {
            string: "+",
            style: "font-size: 1px; padding: 0 " + Math.floor(width/2) + "px; line-height: " + height + "px;"
        }
    }

    // url:图片路径或base64,scale:缩放比例,默认为1
    console.image = function(url, scale) {
        scale = scale || 1;
        var img = new Image();

        img.onload = function() {
            var dim = getBox(this.width * scale, this.height * scale);
            var imgWidth = this.width * scale;
            var imgHeight = this.height * scale;
            console.log("%c" + dim.string, dim.style
                + "background: url(" + url + ");"
                + "background-size: " + imgWidth + "px " + imgHeight + "px;"
                + "color: transparent;"
            );
        };

        img.src = url;
    };
})(console);
使用:
// 支持 图片地址
console.image("图片url",0.5);
// 支持 base64
console.image("base64",0.5);

上面仅展示 console.image() 的代码,因为原库还包含 console.meme() 的实现,用于在控制台生成表情包,感兴趣的同学可以去该库查看详情。

该库上一次更新已经将近10年了,由于近些年 Chrome 控制台中工作方式有变更,导致作者原版实现会使图片重复显示一次。 遇到相同问题的人提了 issues,本文章代码已根据 issues 里提供的解决方案进行了修复。

实现说明:

console.image() 借助于 console.log 能够使用 %c 为打印内容定义样式 的方式进行实现,例如:

// 下面的代码将会在控制台打印出带样式的文本
console.log("这是 %c一条带样式的消息", `
    font-style: italic;
    color: cyan;
    background-color: red;
`);
参考资料 Reference :
https://developer.mozilla.org/zh-CN/docs/Web/API/console

back home