1

How do you create a circle at the centerpoint of a filled path, in an SVG canvas, from generic Javascript or jQuery?

I've tried:

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" />');

but this doesn't seem to do anything, as I can't see any circle created.

Cerin
  • 60,957
  • 96
  • 316
  • 522

2 Answers2

1

You cannot manipulate an svg with code directly. You need to create a new node and insert it:

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>
vqf
  • 2,600
  • 10
  • 16
  • This is close. However, the inserted circle is actually underneath the path, so it still can't be seen. – Cerin Mar 29 '21 at 19:27
  • I did not know the behavior you wanted. You just need to change `insertBefore(c, pth)` at the end of the script with `appendChild(c)`. I just wanted the path to be visible. – vqf Mar 30 '21 at 09:33
1

Jquery add the element on DOM but not on screen:

$(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);
});

Another technich is to include the svg inside div for example and refresh it after appending svg:

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


$("svg").append('<circle ....... fill="red"/>');
$("#divsvg").html($("#divsvg").html());
Frenchy
  • 16,386
  • 3
  • 16
  • 39