HTML Canvas - drawImage() 方法



HTML Canvas 的drawImage() 方法是 Canvas 2D API 提供的一種在 Canvas 元素上繪製/新增影像的不同方式。

語法

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

CanvasRenderingContext2D.drawImage(image, sx, sy, s	w, sh, dx, dy, dw, dh);

引數

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

序號 引數及描述
1

image

要繪製到 Canvas 元素上的影像元素,作為引數傳遞給方法。

2

sx

源影像左上角在 Canvas 中的 x 座標位置。

3

sy

源影像左上角在 Canvas 中的 y 座標位置。

4

sw

源影像的寬度。

5

sh

源影像的高度。

6

dx

在目標 Canvas 中放置源影像左上角的 x 座標位置。

7

dy

在目標 Canvas 中放置源影像左上角的 y 座標位置。

8

dw

在目標 Canvas 中繪製的影像寬度。

9

dh

在目標 Canvas 中繪製的影像高度。

返回值

使用drawImage() 方法和 canvas 上下文建立的影像物件,將影像繪製到 Canvas 元素上。

示例

以下示例使用 HTML Canvas drawImage() 方法將影像繪製到 Canvas 元素上。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="400" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var image = new Image();
      image.onload = function() {
         context.drawImage(image, 50, 50);
      };
      image.src = 'https://tutorialspoint.tw/html5/images/logo.png';
   </script>
</body>
</html>

輸出

網頁上影像返回的輸出如下:

HTML Canvas DrawImage Method

示例

以下示例使用源和目標引數,將部分影像繪製到 Canvas 上,用於drawImage() 方法。

<!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="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var image = new Image();
      image.onload = function() {
         context.drawImage(image, 10, 10, 150, 100, 25, 25, 150, 100);;
      };
      image.src = 'https://tutorialspoint.tw/html5/images/logo.png';
   </script>
</body>
</html>

輸出

網頁上影像返回的輸出如下:

HTML Canvas DrawImage Method
html_canvas_images.htm
廣告

© . All rights reserved.