5

Is there any way to connect two point using a line in SVG .I am having the following to create point in SVG.

<?xml version="1.0" standalone="no"?>

<svg width="200px" height="200px" version="1.1" xmlns="http://www.w3.org/2000/svg">

  <path d="M10 10"/>

  <!-- Points -->

  <circle cx="10" cy="10" r="2" fill="red"/>
  <circle cx="90" cy="90" r="2" fill="red"/>
  <circle cx="90" cy="10" r="2" fill="red"/>
  <circle cx="10" cy="90" r="2" fill="red"/>

</svg>

I need to draw a line between points using jquery functions.

ashu
  • 1,339
  • 7
  • 27
  • 43

2 Answers2

7

You can use a line:

<line x1="10" y1="10" x2="90" y2="90" stroke-width="1" stroke="black"/>

Or a path:

<path d="M10 10 90 90" stroke-width="1" stroke="black"/>

Why do you need jQuery?

Peter Collingridge
  • 10,849
  • 3
  • 44
  • 61
5

If you want to allow the user to connect the dots you need to dynamically change the points of the line or path. There are a few ways to do this however it can be done by tracking the start point then updating the line on mouse move.

var line = $("line");
var svg = $("svg");

var isDown = false;
var startX = 0;
var startY = 0;

$("circle").on("mousedown", function(event){
    isDown = true;
    
    var pOffset = svg.offset();
    startX = event.clientX - pOffset.left,
    startY = event.clientY - pOffset.top;
  
})

$("circle").on("mouseup", function(){
   isDown = false;
})

svg.on("mousemove", function(event){
  if(isDown){
  
   var pOffset = svg.offset(),
            px = event.clientX - pOffset.left,
            py = event.clientY - pOffset.top;
  
   line.attr("x1",startX)
    line.attr("x2",px)
    line.attr("y1",startY)
    line.attr("y2",py)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

<svg width="200px" height="200px" version="1.1" xmlns="http://www.w3.org/2000/svg">

    <circle cx="10" cy="10" r="10" fill="red"/>
    <circle cx="90" cy="90" r="10" fill="red"/>
    <circle cx="90" cy="10" r="10" fill="red"/>
    <circle cx="10" cy="90" r="10" fill="red"/>

     <line id="line" x1="10" y1="10" x2="90" y2="90" stroke="red" />
  </svg>
John
  • 29,788
  • 18
  • 89
  • 130