HTML Canvas - moveTo() Method



The HTML Canvas moveTo() method starts a new path from the given co-ordinates as parameters to the method.

Syntax

Following is the syntax of HTML Canvas moveTo() method −

CanvasRenderingContext2D.moveTo(x, y);

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1 x

The x co-ordinate of the point.

2 y

The y co-ordinate of the point.

Return Value

The method does not return anything directly but changes the cursor position inside the Canvas element.

Example 1

The following example applies the HTML Canvas moveTo() method to the context object and returns the current position of the cursor by window alert.

<!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>

Output

The output returned by the above code on the webpage as −

HTML Canvas MoveTo() Method

The window alert returned by the above code on the webpage as −

HTML Canvas MoveTo() Method

Example 2

The following example draws two lines onto the Canvas element from different positions.

<!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>

Output

The output returned by the above code on the webpage as −

HTML Canvas MoveTo() Method
html_canvas_paths.htm
Advertisements