使用 JS 實現在瀏覽器控制檯打印圖片 console.image()

在前端開發過程中,調試的時候,我門會使用 console.log 等方式查看數據。但對於圖片來說,僅靠展示的數據與結構,是無法想象出圖片最終呈現的樣子的

雖然我們可以把圖片數據通過 img 標籤展示到頁面上,或將圖片下載下來進行預覽。但這樣的調試過程實在是複雜,何不實現一個 console.image() 呢?

先上演示案例:

在線演示 https://bi.cool/bi/W1P1cyq

(chrome 瀏覽器上演示效果)
(chrome 瀏覽器上演示效果)

實現 console.image():

參考 Github 上已實現的庫 https://github.com/adriancooney/console.image Star 1.8k(本文發佈前)。 實現代碼如下:

// 實現 console.image 函數【注意,url如果是網絡圖片必須開啓了跨域訪問才能打印】
console.image = function (url, scale) {
  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 = "red";
      ctx.fillRect(0, 0, c.width, c.height);
      ctx.drawImage(img, 0, 0)
      const dataUri = c.toDataURL('image/png')

      console.log(`%c sup?` ,
        `
          font-size: 1px;
          padding: ${Math.floor((img.height * scale) / 2)}px ${Math.floor((img.width * scale) / 2)}px;
          background-image: url(${dataUri});
          background-repeat: no-repeat;
          background-size: ${img.width * scale}px ${img.height * scale}px;
          color: transparent;
        `
      )
    }
  }
  img.src = url
}

使用方式:

// 支持 圖片地址【注意,url如果是網絡圖片則必須開啓了跨域訪問才能打印圖片】
console.image("替換爲 圖片 url", 0.5);
// 支持 base64
console.image("替換爲 base64 字符出", 1);

上面僅展示 console.image() 的代碼,因爲原庫還包含 console.meme() 的實現,用於在控制檯生成表情包,感興趣的同學可以去該庫查看詳情。

該庫上一次更新已經將近10年了,由於近些年 Chrome 控制檯中工作方式有變更,導致作者原版實現會使圖片重複顯示一次。 遇到相同問題的人提了 issues,本文章代碼已根據 issues 裏提供的解決方案進行了修復。

實現說明:

console.image() 藉助於 console.log 能夠使用 %c 爲打印內容定義樣式 的方式進行實現,例如:

// 下面的代碼將會在控制檯打印出帶樣式的文本
console.log("這是 %c一條帶樣式的消息", `
    font-style: italic;
    color: cyan;
    background-color: red;
`);

下載本案例源碼:https://bi.cool/bi/W1P1cyq

參考資料 Reference :
https://developer.mozilla.org/zh-CN/docs/Web/API/console

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章