Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying SVG path strings by reducing number of nodes

I am generating a large SVG path string that represents a line chart.

Beneath the chart I have a slider for selecting a time range slice. Behind the slider is a mini preview of the whole line chart.

I am currently scaling down the path to generate the preview however in doing so I am ending up with tens of nodes per pixel and therefore far more detail then is necessary. Of course this gives the browser more rendering to do than it has to.

There is plenty of info available on compressing svg strings (gzipping etc), though little on algorithms that actually simplify the path by reducing the nodes.

I am using Raphaeljs and am looking for a javascript based solution. Any ideas?

like image 668
hacklikecrack Avatar asked Dec 05 '12 18:12

hacklikecrack


1 Answers

Simplify.js is probably what you're looking after.

Given your line chart consists of straight line segments only (which by definition it should), you can use it like this:

  var tolerance = 3
  var pathSegArray = []
  for (var i=0; i<path.pathSegList.numberOfItems; i++) {
    pathSegArray.push(path.pathSegList.getItem(i))
  }
  var newPathArray = simplify(pathSegArray,tolerance)
  var newD = "M";
  for (i=0; i<newPathArray.length; i++) {
    newD += newPathArray[i].x + " " + newPathArray[i].y + " "
  }
  path.setAttribute("d",newD)
like image 187
Thomas W Avatar answered Oct 15 '22 20:10

Thomas W