Languages
[Edit]
EN

JavaScript - draw line on canvas element?

8 points
Created by:
Anisha-Kidd
652

In this short article, we would like to show how to draw line on canvas element using JavaScript.

Simple solution:

// line from x1=10, y1=50 to x2=170, y2=150

context.beginPath();
context.moveTo(10, 50);
context.lineTo(170, 150);
context.stroke();

Preview:

Drawing line on canvas using JavaScript.
Drawing line on canvas using JavaScript.

Practical example

Using JavaScript it is possible to draw line in the following way:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    #my-canvas { border: 1px solid gray; }
    
  </style>
</head>
<body>
  <canvas id="my-canvas" width="200" height="200"></canvas>
  <script>

    function drawLine(context, x1, y1, x2, y2) {
        context.beginPath();
        context.moveTo(x1, y1);
        context.lineTo(x2, y2);
        context.stroke();
    }

    
    // Usage example:
    
    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');

    drawLine(context, 10, 50, 170, 150);  // context, x1, y1, x2, y2

  </script>
</body>
</html>
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join