简体   繁体   中英

HTML Canvas fill not working

Html: HTML:

<canvas id="main"  height="1000" width="1500"></canvas>

JS

  var c = document.getElementById("main");
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.moveTo(200,300);
  ctx.lineTo(800,0);
  ctx.moveTo(800,0);
  ctx.lineTo(1500,300);
  ctx.moveTo(1500,300);
  ctx.lineTo(200,300);
  ctx.closePath();
  ctx.stroke();
  ctx.fillStyle="#8ED6FF";
  ctx.fill();

JSFiddle

Fiddle Updated code

  var c = document.getElementById("main");
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.moveTo(200,300);
  ctx.lineTo(800,0);
  ctx.lineTo(1500,300);
  ctx.lineTo(200,300);
  ctx.closePath();
  ctx.stroke();
  ctx.fillStyle="#8ED6FF";
  ctx.fill();

You dont need to move to same point again as you are already on that point .. so thats why it wasnt working

Sub-paths

This will create (clear) a new main path, so far so good:

ctx.beginPath();

The moveTo() call will create a new sub-path on the main path, here:

ctx.moveTo(200,300);
ctx.lineTo(800,0);

and here:

ctx.moveTo(800,0);
ctx.lineTo(1500,300);

and here:

ctx.moveTo(1500,300);
ctx.lineTo(200,300);

And finally, this will connect first point in path with the last point (in this case they are already overlapping):

ctx.closePath();

Since you now have three sub-paths which represents three unconnected lines, as they all have their own sub-paths, there is no way to fill them as a single shape. And they will not connect simply by having their points overlapping.

Create a continuous line with a single sub-path

You need to make a continuous line on the current sub-path . The lineTo() method will continue from the last point in the current path/sub-path to the coordinate it specifies, so to make a single shape using a single sub-path, you just add a new point to the sub-path by doing:

ctx.beginPath();       // new main path
ctx.moveTo(200,300);   // creates a new sub-path, start point (200, 300)
ctx.lineTo(800,0);     // line from (200, 300) to (800, 0), current point now: (800,0)
ctx.lineTo(1500,300);  // line from (800, 0) to (1500, 300)
//ctx.lineTo(200,300); // not needed because:
ctx.closePath();       // will connect (1500,300) to (200,300) on the current sub-path

Using fill() will also close the path, internally and non-permanent, as it's impossible to fill an open path assuming it has > 2 points (it saves you a line of code, but not very important, just note that stoke() does not close the path for you internally).


Also, a tip not many are aware of : if you intended to draw more closed shapes in the same fillStyle , you could continue with moveTo() after the closePath() to create a new sub-path without the need of using fill() / beginPath() first..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM