javascript问题" for"环

时间:2015-07-29 13:07:21

标签: javascript arrays for-loop

我有以下一些代码,它应该将一系列三角形写入画布元素,但它似乎只通过循环一次(只有第一个三角形写入画布)。我看过各种类似的问题,但没有找到成功找到我的问题,并希望第二双眼睛可以提供帮助。

我在脚本顶部附近定义数组,如下所示:

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();
}

谢谢大家的回复。事实证明我错了我的括号。 (宽*(0.075 + array [i]))等等是预期的。以下是在大约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();
}

2 个答案:

答案 0 :(得分:6)

它实际上会迭代5次,但它只是绘制了与之前相同的三角形,因为数组中的值非常小。尝试使用更大的值:

2
3
2
10

我从w3schools网站获取上述代码的基础,因为我之前从未使用过canvas。

答案 1 :(得分:-1)

尝试使用闭包

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);
}

这应该可以解决问题。