In discussions, Hooray gave the advice a few times to not use .removeAllChildren() to remove the path element and re-draw everything but to just change the data. Previously I've had some trouble figuring out how this ought to be actually coded (largely because the .setData() method wasn't properly documented). Now I've figured out a fast way to do it. So to avoid others having to do the same experiments, here's how it goes in code:
Assume we have a path element my_graph created. Usually we'd draw a plot with
- Code: Select all
.moveTo(x1, y1)
.lineTo(x2, y2)
.lineTo(x3, y3)
(...)
Now, all the canvas Nasal API really does with that command is to fill a section of the properties with two arrays - there ends up being cmd, cmd[1], cmd[2], (...) and coord, coord[1], coord[2], coord[3], (...). The coord array is twice as large as the cmd array.
The cmd array contains a number encoding what to do with the points - moveTo is a 2, lineTo is a 4.
The coord array contains the points in the sequence they arrive - coord = x1, coord[1] = y1, coord[2] = x2, and so on.
So, a fast way to update a plot without deleting it via clearAllChildren and re-plotting it is to use the setData method, a very fast way is to simply create the arrays in Nasal and to write them directly by-passing the canvas API.
Thus, create two Nasal arrays cmd and coord according to the encoding above. Create a canvas path element my_graph where you specify position, line thickness and whatever else.
Then write them using
- Code: Select all
my_graph.setData(cmd, coord);
That internally goes via props.nas which is slow. If you want to utilize the faster setprop() command, instead do something like
- Code: Select all
var path = my_graph._node.getPath();
for (var i = 0; i< size(cmd); i=i+1)
{
index1 = 2 * i;
index2 = index1+1;
setprop(path~"/cmd["~i~"]", cmd[i]);
setprop(path~"/coord["~index1~"]", coord[index1]);
setprop(path~"/coord["~index2~"]", coord[index2]);
}
And that's all.
(if the number of points to be plotted can vary a lot, you need some additional cleverness... but the method is very performance-friendly if you need to deal with hundreds of points).