user2224693
user2224693

Reputation: 122

Error in a Javascript loop to draw on a canvas

Been banging my head against the wall on this one.

I've got a canvas

<canvas id="myCanvas" onclick=point_it(event) width=1450 height=1100 style="border:1px solid #000000;">

I've got my points...

points1 = [
{x: 138, y: 34},
{x: 22, y: 119},
{x: 189, y: 144},
{x: 138, y: 34},
];
points2 = [
{x: 98, y: 185},
{x: 39, y: 268},
{x: 183, y: 301},
{x: 98, y: 185},
{x: 150, y: 115},
];

pointsArray = [points1,points2];

I'm trying to draw them using moveTo, close and fill. I need to repeat a variable number of times, but I just can't get this loop working right...

for (var i = 0; i < pointsArray.length; i++) {
    for (var p = 0; p+1 <= pointsArray[i].length; p++)  {
        if (p<1)    {
        var c2 = myCanvas.getContext('2d');
        c2.beginPath();
        c2.fillStyle = '#'+Math.floor(Math.random()*16777215).toString(16);
        }
        if (p<=pointsArray[i].length)   {
        c2.moveTo(pointsArray[i][p].x, pointsArray[i][p].y);
        }
        if (p=pointsArray[i].length)    {
        c2.closePath();
        c2.fill();
        }
    }
}

I'm new at this. Any help would be appreciated. THANKS!

Upvotes: 0

Views: 43

Answers (1)

John Kugelman
John Kugelman

Reputation: 361615

The = should be == here:

if (p==pointsArray[i].length)    {
     ^^

Upvotes: 1

Related Questions