YouTip LogoYouTip

Canvas Moveto

## HTML Canvas moveTo() Method The `moveTo()` method of the Canvas 2D API moves the starting point of a new sub-path to the specified `(x, y)` coordinates. Unlike drawing methods (such as `lineTo()`), `moveTo()` does not draw anything on the canvas. Instead, it lifts the virtual drawing pen and places it down at a new position, allowing you to start a new path or segment without connecting it to the previous one. --- ## Syntax and Usage ### JavaScript Syntax: ```javascript context.moveTo(x, y); ``` ### Parameter Values: | Parameter | Type | Description | | :--- | :--- | :--- | | `x` | Number | The x-coordinate (horizontal position) of the target point, in pixels. | | `y` | Number | The y-coordinate (vertical position) of the target point, in pixels. | --- ## Code Examples ### Example 1: Drawing a Simple Diagonal Line This example starts a path, moves the pen to the top-left corner `(0, 0)`, and then draws a line to the center-right `(300, 150)`. ```html Your browser does not support the HTML5 canvas tag. ``` ### Example 2: Drawing Multiple Disconnected Lines You can use `moveTo()` multiple times within the same path to draw disconnected shapes or lines. ```javascript var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); // First line segment ctx.moveTo(20, 20); ctx.lineTo(200, 20); // Second line segment (disconnected from the first) ctx.moveTo(20, 80); ctx.lineTo(200, 80); // Render both lines with a single stroke call ctx.strokeStyle = "blue"; ctx.lineWidth = 5; ctx.stroke(); ``` --- ## Key Considerations * **No Visual Output:** The `moveTo()` method only sets the current drawing position. To make paths visible on the screen, you must call the `stroke()` or `fill()` method. * **Starting a Path:** It is highly recommended to call `beginPath()` before starting a new drawing sequence. If you do not call `moveTo()` after `beginPath()`, the first path-drawing command (like `lineTo()`) will often act as a `moveTo()` implicitly. * **Coordinate System:** The canvas coordinate system starts at `(0, 0)` in the top-left corner. The `x` value increases as you move to the right, and the `y` value increases as you move down. --- ## Browser Support The `moveTo()` method is supported by all modern web browsers: * Google Chrome * Mozilla Firefox * Microsoft Edge / Internet Explorer 9+ * Safari * Opera *Note: Internet Explorer 8 and earlier versions do not support the `` element.*
← Canvas RotateCanvas Beginpath β†’