Search code examples
javascriptjquerysvgjquery-svg

Faster SVG Path manipulation


So I want to make a drawing tool using SVG, I'm using a rather naive approach to change the d attribute of my Path:

$("div#drawarea").bind("mousemove", function(ev) {

  ev.preventDefault();

  ev.stopPropagation();

  var pX= (ev.pageX - this.offsetLeft);

  var pY= (ev.pageY - this.offsetTop);

  $path.attr("d", $path.attr("d") + " L" +pX+ "," + pY); //using jquery-svg here to change the d attribute

});

As you can see I do this on the mousemove function. The code works but it becomes unresponsive when the mouse is moving fast creating numerous straight lines when I actually want it to be smooth lines. I think this is happening because the numerous string concatenations I'm doing on the mousemove event (the d attribute on the path can become quite big when the click has been held for long, thousands of characters long in fact).

I'm wondering if there is any native way to add new values at the end of a path instead of manipulating the d attribute directly. I checked the jquery-svg sourcecode and it seems that the library also uses the naive string concatenation mode internally so using its methods would not wield any benefit.

Also I'm wondering if this is the case or if the browser just limits the amount of mousemove events (once every X milliseconds?) that can be triggered and so no performance optimizations would improve this.


Solution

  • Use the SVG pathseg DOM methods. You have to write more complicated code but the browser doesn't have to reparse the whole path attribute. Firefox for instance does take advantage of this and it's quite likely other broswers also.