我有一个JSON文件,包含一堆我想慢慢绘制的点。我读过一个tutorial,但这只画了一行。但我想要的是按顺序绘制几条线(先画一条然后画另一条)并使用不同的起点。这是JSON文件:
{
"data": [
{
"line": {
"color": "#96c23b",
"points": [
{
"x": 1,
"y": 2
},
{
"x": 2,
"y": 3
},
{
"x": 4,
"y": 5
},
{
"x": 7,
"y": 8
}
],
"width": 2.0
},
"type": "line",
"line_id": "1"
},
{
"line": {
"color": "#DF5453",
"points": [
{
"x": 33,
"y": 34
},
{
"x": 34,
"y": 35
},
{
"x": 38,
"y": 39
},
{
"x": 40,
"y": 42
},
{
"x": 45,
"y": 46
}
],
"width": 5.0
},
"type": "line",
"line_id": "2"
}
]
}
绘画速度无关紧要。
我知道如何解析JSON并在没有动画的情况下在画布中绘制线条。这是jQuery的代码:
var points_list = {"data":[
{"line":{"color":"#96c23b","points":[{"x":1,"y":2},{"x":2,"y":3},{"x":4,"y":5},{"x":7,"y":8}],"width":2.0},"type":"line","line_id":"1"},
{"line":{"color":"#DF5453","points":[{"x":33,"y":34},{"x":34,"y":35},{"x":38,"y":39},{"x":40,"y":42},{"x":45,"y":46}],"width":5.0},"type":"line","line_id":"2"}
]}
function drawLines() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d");
$.each(points_list.data, function (key, value) {
var info = value.line;
var color = info.color;
var width = info.width;
var points = info.points;
context.beginPath();
context.moveTo(points[0].x, points[0].y);
context.lineWidth = width;
context.strokeStyle = color;
context.fillStyle = color;
for (var p = 1; p < points.length; p++) {
context.lineTo(points[p].x, points[p].y);
}
context.stroke();
});
}
答案 0 :(得分:0)
以下是使用变量跟踪outerList和innerList的位置的示例。使用lineIndexB跟踪外部列表(points_list.data),使用lineIndexA跟踪innerList(points_list.data.line.points)。
每次激活drawLines函数时,都会绘制下一个线段,然后增加lineIndexA变量。如果线段完成,则lineIndexB递增。
这是使用setTimeout函数使动画工作,它可以很容易地转换为requestAnimationFrame。
var points_list = {"data":[
{"line":{"color":"#96c23b","points":[{"x":1,"y":2},{"x":2,"y":3},{"x":4,"y":5},{"x":7,"y":8}],"width":2.0},"type":"line","line_id":"1"},
{"line":{"color":"#DF5453","points":[{"x":33,"y":34},{"x":34,"y":35},{"x":38,"y":39},{"x":40,"y":42},{"x":45,"y":46}],"width":5.0},"type":"line","line_id":"2"}
]};
var lineIndexA = 1;
var lineIndexB = 0;
var canvas = document.getElementById("canvas");
canvas.width = 500;
canvas.height = 500;
var context = canvas.getContext("2d");
function drawLines() {
var value = points_list.data[lineIndexB];
var info = value.line;
var color = info.color;
var width = info.width;
var points = info.points;
context.beginPath();
context.moveTo(points[lineIndexA-1].x, points[lineIndexA-1].y);
context.lineWidth = width;
context.strokeStyle = color;
context.fillStyle = color;
context.lineTo(points[lineIndexA].x, points[lineIndexA].y);
context.stroke();
lineIndexA = lineIndexA + 1;
if (lineIndexA>points.length-1) {
lineIndexA = 1;
lineIndexB = lineIndexB + 1;
}
//stop the animation if the last line is exhausted...
if (lineIndexB>points_list.data.length-1) return;
setTimeout(function() {
drawLines()
}, 1000);
}
drawLines();
&#13;
<canvas id="canvas"></canvas>
&#13;