【问题标题】:SVG connect two points with a lineSVG用一条线连接两个点
【发布时间】:2019-05-04 19:57:13
【问题描述】:

有什么方法可以在 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 函数在点之间画一条线。

【问题讨论】:

  • 如何使用 jquery 解决这个问题?

标签: svg line draw jquery-svg


【解决方案1】:

你可以使用一行:

<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?

【讨论】:

  • 我需要使用 jquery 在拖动时画线
【解决方案2】:

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多