Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

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

0 contributions
5 points

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>

 

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