我有以下一些代码,它应该将一系列三角形写入画布元素,但它似乎只通过循环一次(只有第一个三角形写入画布)。我看过各种类似的问题,但没有找到成功找到我的问题,并希望第二双眼睛可以提供帮助。
我在脚本顶部附近定义数组,如下所示:
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();
}
答案 0 :(得分:6)
答案 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);
}
这应该可以解决问题。