Languages
[Edit]
EN

JavaScript - fill polygon on canvas element in HTML5 with certain color

8 points
Created by:
Majid-Hajibaba
972

Simple solution:

context.fillStyle = color;

context.beginPath();
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
context.fill();

 

Using JavaScript it is possible to fill polygon with some color in following way.

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

In this example it has been shown how to fill polygon with color. Read this article how to only draw polygon border.

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

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

    function fillPolygon(points, color) {
        if (points.length > 0) {
            context.fillStyle = color; // all css colors are accepted by this property

          	var point = points[0];

            context.beginPath();
            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
            context.fill();
        }
    }

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

    fillPolygon(points, 'yellow');

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