【问题标题】:Stylized console logging程式化的控制台日志记录
【发布时间】:2014-10-09 16:55:51
【问题描述】:

当我在 Facebook 上打开控制台时,我会在下面看到这张图片。他们是怎么做到的?

【问题讨论】:

标签: javascript console


【解决方案1】:

就像在 Firebug 中一样,您可以使用 %c 来设置控制台日志输出的样式。看看我们如何实现 Facebook 的例子:

console.log("%cStop!", "color: red; font-family: sans-serif; font-size: 4.5em; font-weight: bolder; text-shadow: #000 1px 1px;");

由于它支持 CSS 属性,我们甚至可以在其中“绘制”图像:

(function(url) {
  // Create a new `Image` instance
  var image = new Image();

  image.onload = function() {
    // Inside here we already have the dimensions of the loaded image
    var style = [
      // Hacky way of forcing image's viewport using `font-size` and `line-height`
      'font-size: 1px;',
      'line-height: ' + this.height + 'px;',

      // Hacky way of forcing a middle/center anchor point for the image
      'padding: ' + this.height * .5 + 'px ' + this.width * .5 + 'px;',

      // Set image dimensions
      'background-size: ' + this.width + 'px ' + this.height + 'px;',

      // Set image URL
      'background: url('+ url +');'
     ].join(' ');

     // notice the space after %c
     console.log('%c ', style);
  };

  // Actually loads the image
  image.src = url;
})('https://i.cloudup.com/Zqeq2GhGjt-3000x3000.jpeg');

【讨论】:

  • 适用于 Chrome 54.0.2840.100(64 位)
  • +1 用于背景图像示例。知道为什么它还会记录“未定义”吗?我似乎无法摆脱它。
  • @Olivier 尝试做 -> '%c ',注意空格。我看起来是因为你没有渲染任何文本,它没有任何样式。
  • 示例会将图像记录到控制台两次,不太清楚为什么。使用铬 71
  • 很好,它工作。就我而言,我有 2 张图片(重复)。知道为什么吗?
【解决方案2】:

对于那些有两张重复图片的人,请按照@BayyMekenique 的说法添加背景不重复,但也要更改此行:

code'line-height:' + this.height + 'px;', code

到这里:

code'line-height:' + this.height % 2 + 'px;',code

【讨论】:

    【解决方案3】:

    我将此解决方案封装在一个不错的库中:

    https://www.npmjs.com/package/console-log-img

    它还可以显示来自 Canvas 或 Image 元素、ImageBitmap 等的图像!

    【讨论】: