0

What is the best way to make polygon fill with gradient?

Here is my trial but it is not perfect. There should be a better way to do it with no white space in the angle codepen trial

window.onload = function() {
var ce = document.getElementById('ce');
var c = ce.getContext('2d');
// linear gradient fill (second from left)
var gradient = c.createLinearGradient(0, 0, 0, -180);
gradient.addColorStop(0.00, 'white');
gradient.addColorStop(.50, 'black');
gradient.addColorStop(.61, 'black');
gradient.addColorStop(.611, 'white');
gradient.addColorStop(.65, 'black');
gradient.addColorStop(.651, 'white');
gradient.addColorStop(.90, 'white');
gradient.addColorStop(.901, 'rgba(68, 185, 229,.1)');
gradient.addColorStop(.95, 'rgb(12, 80, 180)');
gradient.addColorStop(.96, 'rgb(26, 26, 26)');
gradient.addColorStop(.961, 'white');
gradient.addColorStop(.989, 'white');
gradient.addColorStop(1.00, 'rgb(26, 26, 26)');
c.translate(ce.offsetWidth / 2, ce.offsetHeight / 2);

for (var pie = 0; pie < 5; pie++) {
        c.save();
        c.rotate((pie / 5 * Math.PI * 2) - Math.PI / 5);

        c.beginPath();
        c.moveTo(0, 0);

        c.lineTo(-130, -180);
        c.strokeStyle = "rgba(0, 0, 0, 0)";
        c.stroke();
        c.lineTo(131, -180);
        c.lineTo(0, 0);
        c.closePath();
        c.fillStyle = gradient;
        c.fill();
        c.lineWidth = .5;
        c.lineCap = 'square';
        c.strokeStyle = gradient;
        c.stroke();

        c.restore();
    }
}
Einar Sundgren
  • 4,325
  • 9
  • 40
  • 59
Pierre H
  • 1
  • 1
  • 1
  • Yes, it looks like the anti-aliasing on the wedge-gradient is causing seams to appear. Perhaps use shadowing on a closed pentagon path. Maybe a combination of gradients and shadows. Here's a good SO post on how to cure seams, but it would be difficult to apply since you are using gradients instead of solid colors: http://stackoverflow.com/questions/19319963/how-to-avoid-seams-between-filled-areas-in-canvas – markE Feb 16 '15 at 06:40
  • 1
    markE, I use the overlap by adding c.lineWidth = 1.5; c.lineTo(-130, -180); c.lineTo(130, -180); c.stroke(); after the second stroke. It fill the gap and look much better. Thanks – Pierre H Feb 16 '15 at 14:08

0 Answers0