我有用于绘制到canvas元素的线条的数组,但是,只有两条线被绘制到画布上。当我在每个阵列上执行控制台登录时,实际打印出正确的阵列。谁能告诉我他们为什么不能全部出现?
JS
ctx.beginPath();
for(var i = 0; i < result[0].back_lines.x1.length - 1; i++){
ctx.moveTo(result[0].back_lines.x1[i], result[0].back_lines.y1[i]);
ctx.lineTo(result[0].back_lines.x2[i], result[0].back_lines.y2[i]);
}
ctx.lineWidth = result[0].back_lines.width;
ctx.strokeStyle = result[0].back_lines.stroke;
ctx.stroke();
JSON
[{
"back_lines": {
"width": 6,
"stroke": "#000000",
"x1": [938.4, 621.283, 621.283, 604.267, 549.1, 504.233, 582.817, 582.817, 380.033, 477.5, 477.5, 379.42, 379.42, 344.73, 344.73, 588.37, 646.6, 646.6, 804.33, 804.33, 601.05, 601.05, 597.433, 597.433, 475.433, 362.467, 208.8, 191.217, 191.217, 645.017, 645.017, 866.617, 866.617, 849.25, 849.25, 849.25, 360.033, 360.033, 360.033, 209.8, 209.8, 566.5, 566.5, 611, 611, 360.033, 478.05, 793.083, 793.083, 576, 793.083, 843.32, 843.32, 478.05, 504.233, 504.233, 587.37, 646.07, 646.07, 804.43, 803.4, 622.52, 622.52],
"y1": [258.167, 177.82, 177.82, 258.167, 257.633, 256.633, 257.9, 214.22, 214.22, 366, 484.133, 269.767, 308.82, 308.82, 557.05, 483.5, 483.5, 515, 515, 499.2, 483, 434.3, 141.667, 111.267, 111.267, 111.267, 111.267, 111.267, 586.083, 586.083, 534.783, 534.783, 515.417, 499.2, 499.2, 409.683, 111.267, 111.267, 84.383, 84.383, 577.7, 577.7, 577.7, 577.7, 498.667, 84.383, 84.383, 84.383, 377.233, 377.233, 84.383, 84.383, 120.5, 84.383, 366, 466.15, 467.27, 467.27, 394.52, 394.52, 409.7, 467.8, 403.42],
"x2": [868, 621.283, 621.283, 604.267, 549.1, 504.233, 582.817, 582.817, 380.033, 477.5, 477.5, 379.42, 379.42, 344.73, 344.73, 588.37, 646.6, 646.6, 804.33, 804.33, 601.05, 601.05, 597.433, 597.433, 475.433, 362.467, 208.8, 191.217, 191.217, 645.017, 645.017, 866.617, 866.617, 849.25, 849.25, 849.25, 360.033, 360.033, 360.033, 209.8, 209.8, 566.5, 566.5, 611, 611, 360.033, 478.05, 793.083, 793.083, 576, 793.083, 843.32, 843.32, 478.05, 504.233, 504.233, 587.37, 646.07, 646.07, 804.43, 803.4, 622.52, 622.52],
"y2": [258.167, 225.45, 225.45, 258.167, 257.633, 256.633, 257.9, 214.22, 214.22, 366, 484.133, 269.767, 308.82, 308.82, 557.05, 483.5, 483.5, 515, 515, 499.2, 483, 434.3, 141.667, 111.267, 111.267, 111.267, 111.267, 111.267, 586.083, 586.083, 534.783, 534.783, 515.417, 499.2, 499.2, 409.683, 111.267, 111.267, 84.383, 84.383, 577.7, 577.7, 577.7, 577.7, 498.667, 84.383, 84.383, 84.383, 377.233, 377.233, 84.383, 84.383, 120.5, 84.383, 366, 466.15, 467.27, 467.27, 394.52, 394.52, 409.7, 467.8, 403.42]
}
}]
答案 0 :(得分:1)
这里的问题是几乎所有的x1 / x2和y1 / y2对都具有相同的值,前三对除外。这意味着他们不会形成一条线。
也许在某处添加或删除了起点或终点?
此外,我建议使用DRYer代码并将对象分配给变量,而不是重复相同的数组索引/属性访问,并且在for
循环中有一个off-by-one错误:
var backLines = result[0].back_lines,
x1 = backLines.x1,
y1 = backLines.y1,
x2 = backLines.x2,
y2 = backLines.y2;
ctx.beginPath();
ctx.lineWidth = backLines.width;
ctx.strokeStyle = backLines.stroke;
for(var i = 0; i < x1.length; i++){
ctx.moveTo(x1[i], y1[i]);
ctx.lineTo(x2[i], y2[i]);
}
ctx.stroke();