HTML Canvas - getContext() 方法



HTML Canvas 的 getContext() 方法用於獲取/檢索上下文物件。此方法接受一個字串變數作為引數,指定所需的上下文。

如果失敗,此方法將返回 NULL(如果指定的上下文不受支援)。此方法屬於 HTMLCanvasElement 介面。我們不能根據方法提到的內容繪製不同上下文的圖形。

語法

以下是 HTML Canvas getContext() 方法的語法:

HTMLCanvasElement.getContext(context_type);

引數

以下是此方法的引數:

序號 引數及描述
1

context_type

它接受一個包含 Canvas 元素上下文識別符號的字串。引數接受的值為:

  • 2d
  • webgl
  • bitmaprenderer

示例

以下程式碼使用 HTML Canvas getContext() 方法將 Canvas 元素的上下文設定為 2D,並由視窗警報返回。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas" height="300" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
         window.alert("The selected context for the Canvas is - " + context);
      </script>
   </body>
</html>

輸出

以上程式碼在網頁上生成的畫布為:

Html Canvas Width Property

程式碼的視窗警報請求為:

Html Canvas Width Property

示例

以下程式碼透過提供隨機字串設定 Canvas 元素的上下文,並且物件上下文由視窗警報返回。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas" height="200" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('shapes');
         window.alert("The selected context for the Canvas is - " + context);
      </script>
   </body>
</html>

輸出

以上程式碼在網頁上生成的畫布為:

Html Canvas Width Property

程式碼的視窗警報請求為:

Html Canvas Width Property
html_canvas_element.htm
廣告

© . All rights reserved.