4

有什么方法可以使用 SVG 中的一条线连接两个点。我有以下内容在 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>

我需要使用 jquery 函数在点之间画一条线。

4

2 回答 2

6

您可以使用一行:

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

或路径:

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

为什么需要 jQuery?

于 2013-06-24T13:01:06.530 回答
3

如果您想允许用户连接点,您需要动态更改线或路径的点。有几种方法可以做到这一点,但是可以通过跟踪起点然后在鼠标移动时更新线来完成。

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>

于 2019-05-04T11:57:13.673 回答