Languages
[Edit]
EN

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

5 points
Created by:
AnnLen
1771

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>

 

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍