Building a Raphael path object in piecemeal fashion

自古美人都是妖i 提交于 2020-01-01 19:38:53

问题


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:

  1. initializing the path using the Raphael API w/ elem = paper.path()

  2. 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 loop

  3. when 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!