开发者

Javascript/canvas: draw polylines in real-time, what is the optimal data structure?

开发者 https://www.devze.com 2023-01-26 02:06 出处:网络
We\'re using Javascript to draw polylines on a <canvas> element, based on some spatial and time coordinates. Specifically, each point in the line has the following properties:

We're using Javascript to draw polylines on a <canvas> element, based on some spatial and time coordinates. Specifically, each point in the line has the following properties:

* point.x
* point.y
* point.time

meaning that at the time point.time we extend the polyline with an additional segment to point.x/point.y. Being time-based, it's essential that the data structure for the set of all points be as efficient as possible in ter开发者_StackOverflowms of access time.

Intuitively, I believe that a simple array with 3 x N elements (for N nodes) will work best.

Do you have any other suggestions for a suitable structure?


You don't have access to pointers or anything else, so you're basically left to arrays and objecta in JavaScript.

Since your problem is fairly easy, and requires only linear access, a [x, y, t, x, y, t, x, y, t] array should indeed be the fastest way to access the things.

However keep in mind that access to the data won't be the limiting factor here, <canvas> drawing performance, especially in Browser without Hardware Acceleration (which is currently still the majority), will be pretty bad if you draw on either a very big canvas, or many lines in a short amount of time.

Oh and last but not least, test it, don't make assumptions about performance, remember:
"Premature optimization is the root of all evil"


I would prefer that point were an object of object, with time keys storing coordinates, like

   point = {
      <time1> : {
         x : ... ,
         y : ...
      },
      <time2> : {
         x : ... ,
         y : ...
      },
      ...

   }

so you can access directly with point.time.x and point.time.y, since x and y are related to a specific time (if I well understood)

instead, with a flat array given a specific time you should make offset operation to retrieve x and y, not so elegant

0

精彩评论

暂无评论...
验证码 换一张
取 消