Remy Houard
Remy Houard

Reputation: 15

HTML Canvas: Fill() not working with no errors in console

Hello I am making a polygon and want to fill it up. But whatever I try to do I can't seem to make it work.

If anyone can point me in the right direction I appreciate it.

https://jsfiddle.net/ygesj1do/4/

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
op = {
  "pts": [{
    "x": 40,
    "y": 13.5
  }, {
    "x": 60,
    "y": 27.75
  }, {
    "x": 60,
    "y": 56.25
  }, {
    "x": 40,
    "y": 70.5
  }, {
    "x": 20,
    "y": 56.25
  }, {
    "x": 20,
    "y": 27.75
  }],
  "color": "#00F",
  "fillcolor": "#FF0000",
  "lineWidth": 1
};

ctx.save();
ctx.strokeStyle = op.color;
ctx.fillStyle = op.fillcolor;
ctx.lineWidth = op.lineWidth;
ctx.beginPath();

for (i = 1; i <= op.pts.length; i++) {
  if (i == op.pts.length) {
    ctx.moveTo(op.pts[i - 1].x, op.pts[i - 1].y);
    ctx.lineTo(op.pts[0].x, op.pts[0].y);
  } else {
    ctx.moveTo(op.pts[i - 1].x, op.pts[i - 1].y);
    ctx.lineTo(op.pts[i].x, op.pts[i].y);
  }
}

ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

Upvotes: 1

Views: 441

Answers (1)

ADuboisForge
ADuboisForge

Reputation: 121

You only need to use moveTo() once for each path after beginPath() then just use lineTo() after that. Once you do all of the lineTo()'s in the for loop, then you can do the ctx.fill() to get it to work.

Here's the updated part of the code:


/* set moveTo() once before for loop */
ctx.moveTo(op.pts[0].x,op.pts[0].y);



/*then in the for loop just use lineTo(), using lineTo() will keep track of the last endpoint on the current path so you don't need to use moveTo() unless you are starting a new path.*/

        for (i=1;i<=op.pts.length;i++) {
            if (i==op.pts.length) {
                ctx.lineTo(op.pts[0].x,op.pts[0].y);
            } else {
                ctx.lineTo(op.pts[i].x,op.pts[i].y);
            }
        }

/* now the following will work */
    ctx.closePath();
    ctx.fill();


Hope this helps!

Upvotes: 1

Related Questions