【问题标题】:Creating an SVG circle relative to a path in Javascript [duplicate]在Javascript中创建相对于路径的SVG圆[重复]
【发布时间】:2021-06-25 14:16:45
【问题描述】:

如何使用通用 Javascript 或 jQuery 在 SVG 画布中的填充路径的中心点创建一个圆圈?

我试过了:

var path = $('#path123')[0];
var bb = path.getBBox();
var cx = bb.x + bb.width/2;
var cy = bb.y + bb.height/2;
$('svg').append('<circle cx="'+cx+'" cy="'+cy+'" r="40" stroke="black" stroke-width="3" fill="red" />');

但这似乎没有任何作用,因为我看不到任何创建的圈子。

【问题讨论】:

  • 你能用path123显示你的html吗?

标签: javascript jquery svg


【解决方案1】:

您不能直接使用代码操作 svg。您需要创建一个新节点并插入它:

var pth = $('#path123')[0];
var bb = pth.getBBox();
var cx = bb.x + bb.width/2;
var cy = bb.y + bb.height/2;
let c = document.createElementNS('http://www.w3.org/2000/svg','circle');
c.setAttribute('cx', cx);
c.setAttribute('cy', cy);
c.setAttribute('r', 40);
c.setAttribute('fill', "red");
c.setAttribute('stroke', 'black');
c.setAttribute('stroke-width', 3);
$('svg')[0].insertBefore(c, pth);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg width="300" height="300">
  <path id="path123" d="M 100 100 l 50 50 l -50 0 Z" />
</svg>

【讨论】:

  • 这很接近。但是,插入的圆圈实际上是在路径下方,所以仍然看不到。
  • 我不知道你想要的行为。您只需将脚本末尾的insertBefore(c, pth) 更改为appendChild(c)。我只是想让路径可见。
【解决方案2】:

Jquery 在 DOM 上添加元素,但不在屏幕上:

$(document).ready(function() {
  var path = $('#path123')[0];
  var bb = path.getBBox();
  var cx = bb.x + bb.width / 2;
  var cy = bb.y + bb.height / 2;
  
  var obj = document.createElementNS("http://www.w3.org/2000/svg", "circle");
  obj.setAttributeNS(null, "cx", cx);
  obj.setAttributeNS(null, "cy", cy);
  obj.setAttributeNS(null, "r", 40);
  obj.setAttributeNS(null, "stroke", "black");
  obj.setAttributeNS(null, "stroke-width", 3);
  obj.setAttributeNS(null, "fill", "red");
  $("svg")[0].append(obj,pth);
});

另一种技术是例如在 div 中包含 svg 并在附加 svg 后刷新它:

  <div id="divsvg"
    <svg width="300" height="300">
      <path id="path123" d="........." />
    </svg>
  </div>


$("svg").append('<circle ....... fill="red"/>');
$("#divsvg").html($("#divsvg").html());

【讨论】:

    猜你喜欢
    • 2011-08-08
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2021-12-27
    • 1970-01-01
    • 2019-09-21
    相关资源
    最近更新 更多