Someone
Someone

Reputation: 121

CanvasRenderingContext2D.fill() does not seem to work

I'm making a simply polygon draw method in HTML5 canvas. It will successfully outline the shape, but it will not fill it, even though it has been instructed to:

function PhysicsObj(Position /*Vector*/,Vertices /*Vector Array*/)
        {
            this.Position = Position
            this.Vertices = Vertices
            this.Velocity = new Vector(0,0);
            this.Colour = "rgb(100,100,100)";

            this.draw = function()
            {
                ctx.beginPath();
                for(var point=0; point<Vertices.length-1; point++)
                {
                    ctx.moveTo(Vertices[point].X+Position.X,Vertices[point].Y+Position.Y);
                    ctx.lineTo(Vertices[point+1].X+Position.X,Vertices[point+1].Y+Position.Y);
                }
                ctx.moveTo(Vertices[point].X+Position.X,Vertices[point].Y+Position.Y);
                ctx.lineTo(Vertices[0].X+Position.X,Vertices[0].Y+Position.Y);
                ctx.closePath();
                ctx.fillStyle = this.Colour;
                ctx.fill();
                ctx.strokeStyle = this.Colour;
                ctx.stroke();
            }
        }

        var Polygon = new PhysicsObj(new Vector(100,100),[new Vector(50,50),new Vector(-50,50), new Vector(0,125)]);
        Polygon.draw();

The method simply takes several vertices, and connects them into a path. It simply will not fill; I cannot figure out how to use the fill method.

Upvotes: 0

Views: 146

Answers (1)

markE
markE

Reputation: 105015

Eliminate the extra moveTo commands:

var PositionX=50;
var PositionY=50;

var Vertices=[
    {X:10,Y:10},
    {X:100,Y:10},
    {X:50,Y:50}
];

ctx.beginPath();
ctx.moveTo(Vertices[0].X+PositionX,Vertices[0].Y+PositionY);
for(var point=1; point<Vertices.length; point++)
{
    ctx.lineTo(Vertices[point].X+PositionX,Vertices[point].Y+PositionY);
}
ctx.lineTo(Vertices[0].X+PositionX,Vertices[0].Y+PositionY);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
ctx.strokeStyle = "black";
ctx.stroke();

Upvotes: 2

Related Questions