Raphael draw path with mouse

邮差的信 提交于 2019-11-29 03:35:34

问题


I'm using the raphael javascript library, and I'd like to draw a straight line using the mouse. I'd like to let the user click somewhere, place a single point of the path, and then have the line follow the mouse until they click again, at which point the line is placed permanently on the canvas.

Right now the only way to do that seems to be to create a path when they click, constantly remove and redraw it when they move the mouse, and then create it once more when they click again, keeping track of the drawing mode all throughoutj. While this works, it's a bit convoluted and messy (especially building up 'Mx yLx y' strings to define the new path), and I was wondering if there's a better way to do this. The raphael documentation on path leaves a little to be desired.

Thanks!


回答1:


From what I can tell you're doing it right. The only thing I will ad is that you could animate from one path to another instead of replacing the old one and you could enforce a maximum frame rate (say no more than 5 path updates per second, but you need to try and see what works for you).

As for the documentation for path I don't think there is anything more that can be said. The method accepts a SVG path string and draws it. What you need to read may be the SVG documentation for path.

How to animate a path:

p = canvas.path("M0 0L100 0");
p.animate({path: [["M", 0, 0], ["L", 0, 100]]}, 4000);



回答2:


There's actually a better way to do this, using path.attr('path'). path is an array of path part arrays, e.g.

[
  ['M', 100, 100],
  ['L', 150, 150],
  ['L', 200, 150],
  ['Z']
]

If you update it then you don't need to draw the path from scratch each time.

Raphael.el.addPart = function (point) {
  var pathParts = this.attr('path') || [];
  pathParts.push(point);
  this.attr('path', pathParts);
};

var path = paper.path();
path.addPart(['M', 100, 100]); //moveto 100, 100
path.addPart(['L', 150, 150]); //lineto 150, 150
path.addPart(['L', 200, 150]); //lineto 200, 150
path.addPart(['Z']);           //closepath


来源:https://stackoverflow.com/questions/4356929/raphael-draw-path-with-mouse

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