Filling a polygon on canvas

How can I fill the path that I painted in red?

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

I tried to use fill, but it does not fill my path as I want - to fill the red path, but instead it only fills the diagonal part (comment out ctx.fill () to see the full path that I want to fill) Code, which draws a 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();

}

+4
source share
2 answers

Hope this is what you wanted: http://jsfiddle.net/MVXZu/2/

if (i == 13) {}, moveTo lineTo. , .

. , , . .

+2
  • beginPath
  • moveTo, (. , closePath()). lineTo. ...

: http://jsfiddle.net/MVXZu/3/

-:

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();
+3

Source: https://habr.com/ru/post/1502509/


All Articles