HTML Canvas - translate() 方法



Canvas API 的 HTML Canvas translate() 方法將 Canvas 元素內部的平移矩陣新增到當前矩陣中。

語法

以下為 HTML Canvas translate() 方法的語法

 
CanvasRenderingContext2D.translate(x, y); 

引數

以下列出了該方法的引數列表-

序號 引數和描述
1

x

水平方向的移動距離。

2

y

垂直方向的移動距離。

返回值

它將在呼叫此方法時返回物件的平移變換矩陣。

示例

以下示例平移 Canvas 座標並使用 HTML Canvas translate() 方法在 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.translate(10, 10);
      context.fillStyle = 'blue';
      context.fillRect(25, 25, 150, 100);
   </script>
</body>
</html>

輸出

以下程式碼在網頁上返回的輸出為-

HTML Canvas Translate Method

示例

以下示例使用 translate() 方法在 Canvas 元素上平移一條線。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="150" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.translate(10, 10);
      context.strokeStyle = 'blue';
      context.moveTo(10, 10);
      context.lineTo(100, 100);
      context.stroke();
   </script>
</body>
</html>

輸出

以下程式碼在網頁上返回的輸出為-

HTML Canvas Translate Method
html_canvas_shadows_and_transformations.htm
廣告
© . All rights reserved.