Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - draw polygon on canvas element in HTML5

0 contributions
1 points

Simple solution:

context.moveTo(20, 40);   // point 1
context.lineTo(70, 150);  // point 2
context.lineTo(110, 80);  // point 3
context.lineTo(180, 170); // point 4
context.lineTo(150, 70);  // point 5
context.closePath();      // go back to point 1


Using JavaScript it is possible to draw polygon in following way.

1. lineTo(), closePath() and stroke() methods example

In this example it has been shown how to draw stroke / border of polygon. Read this article how to fill polygon with certain color.

// ONLINE-RUNNER:browser;

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

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

    function drawPolygon(points) {
        if (points.length > 0) {
            var point = points[0];
            context.moveTo(point.x, point.y);   // point 1
            for (var i = 1; i < points.length; ++i) {
                point = points[i];
                context.lineTo(point.x, point.y);
            context.closePath();      // go back to point 1

    var points = [ 
        {x: 20, y: 40},
        {x: 70, y: 150},
        {x: 110, y: 80},
        {x: 180, y: 170},
        {x: 150, y: 70}



Merged questions

  1.  How to draw polygon border on HTML5 canvas in JavaScript?
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more