问题
I'm trying to create a little free-hand drawing app, and to figure out a way to add path segments (e.g. "L10,10") to a Raphael path Element. This answer suggests that isn't possible.
I've tried doing something like:
var e = paper.path("M0,0L100,100")
e.attr("path").push(["L",50,100])
...which does alter the array returned by e.attr("path")
but doesn't change the graphic, so I guess this isn't supported behavior.
回答1:
It looks like you have to call the setter version of .attr() to update the display. The following seems to work:
var e = paper.path("M0,0L100,100");
e.attr("path").push(["L",50,100]);
e.attr("path", e.attr("path"));
although this does look pretty clumsy. I don't really see a better way to do it using push(), though.
回答2:
After looking through the Raphael 2 source I figured out a method to create an incremental path efficiently, by:
initializing the path using the Raphael API w/
elem = paper.path()
attaching the mousemove handler to alter the SVG DOM path directly, via
elem.node.setAttribute("d", elem.node.getAttribute("d")+newLineSegment);
Raphael uses the 'd' attribute to set path string internally so this should be cross-browser compatible AFAICT (Update: actually I'm mistaken; this only works for the SVG-compatible browsers, not VML), while bypassing a whole mess of code we don't need to have run on an inner loopwhen done drawing, set the path attribute for the path element explicitly through Raphael's API, so it can do all the proper housekeeping on the
Element
e.g.:elem.attr( {path: elem.node.getAttribute("d") })
This performs reasonably well on Chrome, and other modern browsers I tested on.
I've finished a jQuery UI widget for a sketchpad that uses this. Please leave a comment if you would find such a thing useful as open source. If there's interest I'll see if I can make that happen.
回答3:
I can conform that this works:
var arr = somePath.attrs.path;
arr.push(["L", x, y]);
somePath.attr({path: arr});
来源:https://stackoverflow.com/questions/8608368/building-a-raphael-path-object-in-piecemeal-fashion