CanvasRenderingContext2D:getContextAttributes() 方法

Baseline 2023
新推出

自 2023 年 8 月起,此功能已在最新的裝置和瀏覽器版本中可用。此功能可能不適用於舊裝置或瀏覽器。

CanvasRenderingContext2D.getContextAttributes() 方法返回一個包含上下文所用屬性的物件。

請注意,在使用 HTMLCanvasElement.getContext() 建立上下文時,可以請求上下文屬性,但實際支援和使用的屬性可能會有所不同。

語法

js
getContextAttributes()

引數

無。

返回值

一個 CanvasRenderingContext2DSettings 物件,其中包含實際的上下文引數。它具有以下成員

alpha 可選

一個布林值,指示 canvas 是否包含 alpha 通道。如果為 false,則背景始終是不透明的,這可以加快透明內容和影像的繪製速度。

colorSpace 可選

指示渲染上下文的顏色空間。可能的值是

colorType 可選

指示渲染上下文的顏色型別。可能的值是

  • "unorm8":表示顏色通道為 8 位無符號值。這是預設值。
  • "float16":表示顏色通道為 16 位浮點值。
desynchronized 可選

一個布林值,指示使用者代理是否透過將 canvas 繪製週期與事件迴圈進行非同步處理來降低延遲。

willReadFrequently 可選

一個布林值,指示此 canvas 是否使用軟體加速(而不是硬體加速)來透過 getImageData() 支援頻繁的讀回操作。

示例

此示例展示瞭如何在建立 canvas 上下文時指定上下文屬性,然後呼叫 getContextAttributes() 來讀取瀏覽器使用的實際引數。

首先,我們使用 HTMLCanvasElement.getContext() 建立一個上下文,僅指定一個上下文屬性。

js
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d", { alpha: false });

如果 getContextAttributes() 方法受支援,我們使用它來讀取瀏覽器使用的實際屬性(包括我們明確指定的那些)。

js
if (ctx.getContextAttributes) {
  const attributes = ctx.getContextAttributes();
  log(JSON.stringify(attributes));
} else {
  log("CanvasRenderingContext2D.getContextAttributes() is not supported");
}

根據瀏覽器支援的屬性,下面的日誌應顯示一個類似以下的字串: {alpha: false, colorSpace: 'srgb', desynchronized: false, willReadFrequently: false}

規範

規範
HTML
# 2dcontext:dom-context-2d-canvas-getcontextattributes-2

瀏覽器相容性

另見