Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill polygon on canvas

How can I fill the path that I've drawn in red?

http://jsfiddle.net/MVXZu/1/

I've tried to use fill but it doesn't fill my path as I want it to - that is to fill in the red outline - but instead it fills only a diagonal portion (comment out the ctx.fill(); to see the full outline I want to fill) The code that's drawing the line is this:

//loop through the data
ctx.beginPath();
for (var i = 0; i < data.length; i++) {
ctx.lineWidth=3;
ctx.lineCap = 'round';
ctx.strokeStyle = 'red';
ctx.moveTo(linePosX,linePosY);
ctx.lineTo((i*cellWidth) + cellWidth + padding,(tableHeight + padding) - data[i].v);
linePosX = i*cellWidth + padding + cellWidth;
linePosY = (tableHeight + padding) - data[i].v;
if(i == 13) {

    ctx.lineTo(linePosX,tableHeight+padding);
    ctx.lineTo(padding,tableHeight+padding);
}

   ctx.fillStyle="red";
   ctx.fill();
   ctx.stroke();
   ctx.closePath();

}

like image 482
Mike Rifgin Avatar asked Sep 16 '13 22:09

Mike Rifgin


2 Answers

  • Don't put the beginPath into the loop
  • Don't use moveTo, as that creates a new polygon to fill (see it here, as the result of closePath()). You're at the correct position after the before lineTo anyway. Without it it works better…

Here's the fixed fiddle: http://jsfiddle.net/MVXZu/3/

Pseudo-code:

ctx.beginPath();
// set ctx styles
ctx.moveTo( bottom-left corner );
for each (point in data) {
    ctx.lineTo(point);
}
ctx.lineTo( bottom-right corner );
ctx.closePath(); // automatically moves back to bottom left corner
ctx.fill();
like image 115
Bergi Avatar answered Oct 13 '22 07:10

Bergi


Hopefully this is what you were wanting: http://jsfiddle.net/MVXZu/2/

Because you were only running some of the code if (i == 13) {}, only the moveTo and the first lineTo were getting called. This was resulting in a line at the top of the section, but not a box to fill.

I moved a lot of the drawing outside of the loop. It creates the first point in the bottom left of the graph, then the points along the top, then the point in the bottom right. Then it fills in the whole graph after the path is finished.

like image 29
ZachRabbit Avatar answered Oct 13 '22 07:10

ZachRabbit