K
K
kosta_92017-07-24 13:47:07
JavaScript
kosta_9, 2017-07-24 13:47:07

How to draw lines with the mouse in SVG?

Good day everyone. Faced a problem (due to lack of knowledge) in drawing a line with the mouse in SVG. There is the following code:
...

var s = Snap(500, 200);
            var line1 = s.line(20, 30, 100, 100);
            line1.attr ({
                stroke: "black"
            });
 
            // Определение координат мыши__________________
            var mouse = {
            getX: function(e) {
            return e.offsetX;
            },
            getY: function(e) {
            return e.offsetY;
            }
            };
                        //_____________________________________________
 
            s.mousedown (function (e){
            line1.attr({x1: mouse.getX(e)});
            line1.attr({y1: mouse.getY(e)});
            
            
            s.mousemove (function(e){
            line1.attr('x2', mouse.getX(e));
            line1.attr('y2', mouse.getY(e));
            })
            })
            s.mouseup (function(e){
            line1.attr({x2: mouse.getX(e)});
            line1.attr({y2: mouse.getY(e)});
                })

This is the maximum that was enough knowledge. In my example, there is only a change in the coordinates of the line, and then it does not get rid of mousemove when the mouse is released. I would like to implement the following: when you click on the canvas - to create the beginning of the line, when moving - the other end of the line was attached to the cursor, that is, dynamic drawing, and when released, the line was fixed in its place.
Used the Snap.svg library. Please give advice or code example for this rendering, not necessarily in Snap. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2017-07-24
@kosta_9

Click to start/end drawing
https://jsfiddle.net/bc1n82zc/7/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question