HTML Canvas - 畫布屬性



Canvas API 的 HTML Canvas 屬性是 Canvas 上下文物件的引用。它幫助我們定義 canvas 標籤並使用它來使用 canvas 物件開發圖形。這是透過使用 JavaScript 程式碼實現的。

可能的輸入值

它獲取 canvas 標籤和提供的程式碼片段,並構造一個具有指定尺寸和給定樣式的新 Canvas 元素物件。

可以使用此上下文提供給 Canvas 元素,並可以使用可用方法和屬性渲染圖形。

示例

以下示例演示如何使用 HTML 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" width="200" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
         console.log(context.canvas);
      </script>
   </body>
</html>

輸出

上述程式碼在網頁控制檯中返回的輸出為:

Html Canvas Property

在網頁上看到的輸出為:

Html Canvas Property Output

示例

以下示例演示如何使用 canvas 屬性生成新的上下文物件,並透過增加大小和新增顏色來設定邊框樣式。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
         #canvas {
            border: 10px solid green;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas" height="200" width="200"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
      </script>
   </body>
</html>

輸出

上述程式碼在網頁上返回的輸出為:

Html Canvas Property

示例

以下示例演示如何使用 canvas 屬性生成新的上下文物件並填充背景。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }

         #canvas {
            background-color: aqua;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
      </script>
   </body>
</html>

輸出

上述程式碼在網頁上返回的輸出為:

Html Canvas Property

示例

以下示例演示如何使用 canvas 屬性生成新的上下文物件並使用 CSS 樣式設定邊框樣式。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }

         #canvas {
            border: 50px groove grey;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
      </script>
   </body>
</html>

輸出

上述程式碼在網頁上返回的輸出為:

Html Canvas Property
html_canvas_element.htm
廣告
© . All rights reserved.