Chris
Chris

Reputation: 124

Trouble with javascript "for" loop

I have the following bit of code, which is supposed to write a series of triangles to a canvas element, but it appears to only go through the loop one time (only the first triangle is written to the canvas). I've looked at various similar questions, but am not having any success finding my problem, and was hoping a second pair of eyes might help.

I define array near the top of my script as follows:

var array = [0, 0.2, 0.4, 0.6, 0.8];

for (i = 0; i < array.length; i++) 
{
    ctx.beginPath();
    ctx.moveTo(array[i],height);
    ctx.lineTo(((width*0.075) + array[i]),0);
    ctx.lineTo(((width*0.15 + array[i])),(height));
    ctx.closePath();
    ctx.fill();
}

Thank you all for the responses. It turns out that I misplaced my parenthesis. (width * (0.075 + array[i])) and so-on is what was intended. The following is intended behavior, on a canvas that is about 210 px * 30 px.

var array = [0, 0.2, 0.4, 0.6, 0.8];

for (i = 0; i < array.length; i++) 
{
    ctx.beginPath();
    ctx.moveTo(width * array[i], height);
    ctx.lineTo(width * (0.075 + array[i]),0);
    ctx.lineTo(width * (0.15 + array[i]),(height));
    ctx.closePath();
    ctx.fill();
}

Upvotes: 0

Views: 135

Answers (2)

Honinbo Shusaku
Honinbo Shusaku

Reputation: 1511

It actually does iterate through 5 times, but it just draws the same triangle over the previous ones, because the values in the array are so small. Try it with larger values:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var array = [0,40,80,120,160];
var height = 150;
var width = 300;

for (i = 0; i < array.length; i++) 
{
    ctx.beginPath();
    ctx.moveTo(array[i],height);
    ctx.lineTo(((width*0.075) + array[i]),0);
    ctx.lineTo(((width*0.15 + array[i])),(height));
    ctx.closePath();
    ctx.fill();
}

</script>

</body>
</html>

I took the basis for the code above from w3schools site because I've never used canvas before.

Upvotes: 6

IbrahimAsad
IbrahimAsad

Reputation: 516

try to use closure

for (i = 0; i < array.length; i++) 
{
(function(ind){
    ctx.beginPath();
    ctx.moveTo(array[ind],height);
    ctx.lineTo(((width*0.075) + array[ind]),0);
    ctx.lineTo(((width*0.15 + array[ind])),(height));
    ctx.closePath();
    ctx.fill();
})(i);
}

this should fix the problem.

Upvotes: -1

Related Questions