HTML Canvas - moveTo() 方法



HTML Canvas 的 moveTo() 方法從給定的座標(作為方法的引數)開始一條新路徑。

語法

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

CanvasRenderingContext2D.moveTo(x, y);

引數

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

序號 引數及描述
1 x

點的 x 座標。

2 y

點的 y 座標。

返回值

該方法不直接返回任何內容,但會更改 Canvas 元素內部的游標位置。

示例 1

以下示例將 HTML Canvas moveTo() 方法應用於上下文物件,並透過視窗警報返回游標的當前位置。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas" width="350" height="350" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
         const x = canvas.width - 100;
         const y = canvas.height - 100;
         context.moveTo(x, y);
         alert('The cursor is positioned currently at : ' + '(' + x + ', ' + y + ')');
      </script>
   </body>
</html>

輸出

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

HTML Canvas MoveTo() Method

以上程式碼在網頁上返回的視窗警報為:

HTML Canvas MoveTo() Method

示例 2

以下示例在 Canvas 元素上從不同位置繪製兩條線。

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas" width="350" height="350" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
         context.moveTo(50, 50);
         context.lineTo(69, 304);
         context.moveTo(340, 328);
         context.lineTo(23, 47);
         context.stroke();
      </script>
   </body>
</html>

輸出

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

HTML Canvas MoveTo() Method
html_canvas_paths.htm
廣告

© . All rights reserved.