如何在PaperJS / JS中绘制通过JSON请求传递分段/点的线?

时间:2019-06-27 11:05:12

标签: javascript json paperjs

使用PaperJS或JS中的general绘制路径/段的最佳方法是什么,而我为此接收的数据是通过JSON?

1 个答案:

答案 0 :(得分:2)

解析JSON数据的方式取决于其形状,但更普遍的是,在Paper.js中显示点包括绘制一系列圆。
这是sketch,演示了可能的实现。

// This represents the data that you receive, assuming that each point is a [x,y] coordinates array.
const points = [[62, 44], [182, 108], [246, 220], [231, 35], [357, 419], [246, 292], [7, 204], [188, 375], [70, 406], [481, 274], [341, 314], [158, 269], [446, 204], [78, 197], [287, 207], [435, 317], [11, 168], [467, 110], [195, 282], [481, 14], [20, 384], [19, 262], [133, 205], [105, 261], [16, 457], [83, 401], [104, 62], [25, 188], [6, 307], [13, 118], [157, 258], [35, 155], [38, 93], [332, 347], [216, 351], [42, 92], [96, 168], [201, 446], [353, 336], [444, 348], [19, 452], [433, 173], [112, 227], [419, 153], [378, 47], [38, 89], [150, 122], [423, 58], [61, 446], [14, 331]];

for (let [x, y] of points) {
    new Path.Circle({
        center: [x, y],
        radius: 2,
        fillColor: 'orange'
    });
}

此方法的唯一缺点是,如果您有很多要点,则性能可能会成为问题。
如果是这种情况,并且以后不需要与点进行交互,则可以直接使用画布上下文arc()方法直接在画布上绘制圆圈。

// This represents the data that you receive, assuming that each point is a [x,y] coordinates array.
const points = [[62, 44], [182, 108], [246, 220], [231, 35], [357, 419], [246, 292], [7, 204], [188, 375], [70, 406], [481, 274], [341, 314], [158, 269], [446, 204], [78, 197], [287, 207], [435, 317], [11, 168], [467, 110], [195, 282], [481, 14], [20, 384], [19, 262], [133, 205], [105, 261], [16, 457], [83, 401], [104, 62], [25, 188], [6, 307], [13, 118], [157, 258], [35, 155], [38, 93], [332, 347], [216, 351], [42, 92], [96, 168], [201, 446], [353, 336], [444, 348], [19, 452], [433, 173], [112, 227], [419, 153], [378, 47], [38, 89], [150, 122], [423, 58], [61, 446], [14, 331]];

const ctx = document.querySelector('canvas').getContext('2d');

for (let [x, y] of points) {
    ctx.beginPath();
    ctx.arc(x, y, 2, 0, 2 * Math.PI);
    ctx.fill();
}
<canvas width="500" height="500"></canvas>