HTML Canvas - setTransform() 方法



HTML Canvas 的 setTransform() 方法是 Canvas 2D API 的一部分,如果應用於單位矩陣,則會重置當前變換矩陣,然後根據此方法的引數呼叫新的變換。

語法

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

CanvasRenderingContext2D.setTransform(matrix, a, b, c, d, e, f);

引數

以下是此方法的引數列表:

序號 引數及描述
1 矩陣

這是一種可以傳遞給物件的新引數型別。它表示要設定的 2D 變換。矩陣分配如下:

$\begin{Bmatrix} a& c& e \\ b& d& f\\ 0& 0& 1\\ \end{Bmatrix}$

2

a

水平縮放。

3

b

垂直傾斜

4

c

水平傾斜

5

d

垂直縮放

6

e

水平平移

7

f

垂直平移

返回值

應用於 CanvasRenderingContext2D 介面的上下文物件的新的變換繪製在 Canvas 元素上。

示例 1

以下示例將 HTML Canvas setTransform() 方法應用於矩形,並將其繪製到 Canvas 元素上。

<!DOCTYPE html>
<html lang="en">
<head>    
   <title>Reference API</title>
   <style>
   body {
     margin: 10px;
     padding: 10px;
   }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas=document.getElementById('canvas');
      var context=canvas.getContext('2d');
      context.fillStyle='purple';
      context.setTransform(1, 0.5, 0.7, 0.9, 0.8, 0);
      context.fillRect(15, 15, 100, 60);
   </script>
</body>
</html>

輸出

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

HTML Canvas SetTransform Method

示例 2

以下示例使用 setTransform() 方法將變換矩陣應用於 Canvas 元素內繪製的圓形。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.fillStyle = 'purple';
      context.setTransform(1, 0.5, 0.7, 0.9, 0.8, 0);
      context.arc(100, 50, 75, 0, 2 * Math.PI);
      context.fill();
   </script>
</body>
</html>

輸出

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

HTML Canvas SetTransform Method
html_canvas_shadows_and_transformations.htm
廣告

© . All rights reserved.