SVG connect two points with a line
Asked Answered
H

2

6

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.

Hershel answered 24/6, 2013 at 10:9 Comment(0)
A
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?

Aluin answered 24/6, 2013 at 13:1 Comment(1)
I need to draw line on draging using jqueryHershel
L
6

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>
Lilianaliliane answered 4/5, 2019 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.