- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to draw a line with lineTo() in HTML5?
The Canvas 2D API's lineTo() method, which connects the last point of the current sub-path to the given (x, y) coordinates, adds a straight line to the sub-path.
The lineTo() method expands the canvas by adding a new point and drawing a line to it from the previous point (this method does not draw the line).
Syntax
Following is the syntax to draw a line
lineTo(x, y)
let’s look into the following examples to get a better idea on how to draw a line with line to in HTML5.
Example 1
In the following example we are using function draw() along with lineto() to draw a line.
<!DOCTYPE html> <html> <body> <canvas id="canvas" height="400" width="500"> </canvas> <script> function draw() { const canvas = document.querySelector('#canvas'); if (!canvas.getContext) { return; } const ctx = canvas.getContext('2d'); ctx.strokeStyle = 'red'; ctx.lineWidth = 5; ctx.beginPath(); ctx.moveTo(100, 100); ctx.lineTo(300, 100); ctx.stroke(); } draw(); </script> </body> </html>
On executing the above script, it will generate the output, displaying the canvas line drawn on the webpage.
Example 2
Let's look another example we are using lineto() to draw a line in our canvas.
<!DOCTYPE html> <html> <body> <canvas id="Varma" width="300" height="150"></canvas> <script> var c = document.getElementById("Varma"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(20, 100); ctx.lineTo(70, 100); ctx.stroke(); </script> </body> </html>
When the script gets executed,it will display the canvas line drawn in the shape of an "L" on the webpage.