canvas 適配瀏覽器可視窗口出現滾動條問題

canvas 適配瀏覽器可視窗口出現滾動條問題

一般來說,對於前端數據可視化工程師來說,canvas 是個極好的工具。

既能用 canvas 2d 調用 CanvasRenderingContext2D 的 api 來繪製各種圖表、圖形,這個主要依賴 cpu 來計算。也能用 canvas 3d webgl 來繪製各種圖形、圖表,它主要依賴 gpu 來繪製各種圖形。

最近突然遇到一個問題是,我有一個 canvas 元素,我想每次出來都讓他自適應屏幕可視區域的大小。

我第一反應就是,直接設置 css 屬性 width: 100%; height: 100% ,但是馬上就被我自己給否決了。

因爲出於以往的經驗來說,在 canvas 元素上用設置 100% 這種參數,應該是達不到這種效果的。

爲了驗證我的猜想,於是我開始寫代碼驗證了:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      * {
        padding: 0px;
        margin: 0px;
        border: 0;
      }
      html,
      body {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <script>
      const canvas = document.createElement('canvas');
      document.body.appendChild(canvas);
      canvas.style.width = 100 + '%';
      canvas.style.height = 100 + '%';
      canvas.style.background = '#aaa';
    </script>
  </body>
</html>

然後在瀏覽器中運行頁面:
image.png

果然不出所料,可以是可以,但是會出現側邊滾動條,這是爲什麼呢?爲什麼 div 就沒有這種全屏滾動條呢?

帶着這種懷疑,我打開控制檯,看了一下,原來 canvas 元素的 style 屬性中的 display 爲 inline,是不是因爲這個原因導致的呢?

image.png

於是我改了改其 display 屬性值,將其改爲 block,發現果然如我所料,滾動條消失了:
image.png

看來碰到問題的時候,不能急於全盤否定,需要先測試一下,深究一番到底是什麼原因導致結果與預想的不符。

知道原因了以後,那麼我們就明白了,可以用哪些方式達到我們想要的效果了。

但是需要注意的一點是,對於 canvas 來說,style 的 width 和 height 不等同於畫布的大小,畫布的大小是 HTMLCanvasElement.prototype.width 和 HTMLCanvasElement.prototype.height 這兩個屬性控制的,可以參考一下 html 標準中的這一段話:

The [canvas](https://html.spec.whatwg.org/multipage/canvas.html#the-canvas-element) element has two attributes to control the size of the element’s bitmap: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The [width](https://html.spec.whatwg.org/multipage/canvas.html#attr-canvas-width) attribute defaults to 300, and the [height](https://html.spec.whatwg.org/multipage/canvas.html#attr-canvas-height) attribute defaults to 150.

也就是說,canvas.width 和 canvas.height 纔是真正控制畫布大小的。

一般正常情況下,會將 canvas.width 和 canvas.height 大小調整到與 canvas.style.width 和 canvas.style.height 等大。

不然會導致如下圖所示的效果:

image.png

兩個圖的 canvas.width 和 canvas.height 屬性均爲 100,但是由於 canvas.style.width 和 canvas.style.height 屬性不同,導致一張圖呈現被拉伸的模糊的效果,一般情況下,我們不希望會出現這樣的效果。

所以接下來,我會總結一下,如果想要將 canvas 畫布設置爲適配瀏覽器窗口大小,需要幾個步驟:

  1. 選擇一種將 canvas 元素適配窗口的方案,無論是百分比、 vw 等 css 方法,還是採用 js 獲取窗口尺寸再調整的方法,請注意一定要調整下 canvas 元素的 display 屬性或者將父元素的 overflow 設置爲 hidden,否則會出現滾動條。
  2. 將 canvas.width 和 canvas.height 設置爲與其樣式尺寸等大。
  3. 開始編程吧。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章