Matthew Riches
Matthew Riches

Reputation: 2286

HTML5 Canvas Fill Complicated Shape

I have the following snipper of code:

      context.beginPath();
      context.moveTo(284 + xoff, 119 + yoff);
      context.bezierCurveTo(46 + xoff, 189 + yoff, 39 + xoff, 60 + yoff, 243 + xoff, 29 + yoff);
      context.moveTo(284 + xoff, 119 + yoff);
      context.bezierCurveTo(239 + xoff, 130 + yoff, 104 + xoff, 105 + yoff, 243 + xoff, 29 + yoff);

      context.strokeStyle = "#e2252c"; // line color
      context.stroke();
      context.closePath();

Everytime I fill this shape despite the outline being a kind of saturn ring, the fill seems to fill it in as a half oval, is there a way you can make fill only fill between the lines I have set. I have tried clipping but this didn't work ever. Am I missing something?

Upvotes: 1

Views: 1789

Answers (1)

Michael Minella
Michael Minella

Reputation: 56

The issue here is that you are jumping around. Think of creating your path like working with an Etch-a-Sketch. You can't draw one line, then jump over to another point and draw another. Instead you have to draw one, then continue from where you stopped. In order for this to work, you need to do the following:

  1. beginPath
  2. moveTo
  3. bezierCurve for first line to opposite end point
  4. bezierCurve back to to the point that you did the moveTo to
  5. stroke
  6. fill

The following worked for me (just my second curve needs to be tweaked to meet your needs):

context.beginPath();
context.moveTo(284 + xoff, 119 + yoff);
context.bezierCurveTo(46 + xoff, 189 + yoff, 39 + xoff, 60 + yoff, 243 + xoff, 29 + yoff);
context.bezierCurveTo(46 + xoff, 189 + yoff, 39 + xoff, 60 + yoff, 284 + xoff, 119 + yoff);
context.closePath();
context.strokeStyle = "#e2252c"; // line color
context.fillStyle = "#2C6BA1";
context.stroke();
context.fill();

Upvotes: 4

Related Questions