Как добавить SVG круг внутри тега - PullRequest
0 голосов
/ 27 апреля 2018

enter image description here Следующий тег находится внутри тега:

<circle cx="111.70110487400142" cy="134.60212936975006" r="10" stroke="#000000" fill="#000000" stroke-width="0" data-pdf-annotate-id="8e1b063b-ec08-4c73-8b86-d8e8cce5615e" data-pdf-annotate-type="fillcircle" aria-hidden="true" transform="scale(1.33) rotate(0) translate(0, 0)"></circle>

Теперь я должен добавить этот сгенерированный круг внутри тега типа

<a href="#">
<circle cx="111.70110487400142" cy="134.60212936975006" r="10" stroke="#000000" fill="#000000" stroke-width="0" data-pdf-annotate-id="8e1b063b-ec08-4c73-8b86-d8e8cce5615e" data-pdf-annotate-type="fillcircle" aria-hidden="true" transform="scale(1.33) rotate(0) translate(0, 0)"></circle>
</a>

Изменено:

<svg class="annotationLayer" width="1118.53" height="1582.7" data-pdf-annotate-container="true" data-pdf-annotate-viewport="{&quot;viewBox&quot;:[0,0,841,1190],&quot;scale&quot;:1.33,&quot;rotation&quot;:0,&quot;offsetX&quot;:0,&quot;offsetY&quot;:0,&quot;transform&quot;:[1.33,0,0,-1.33,0,1582.7],&quot;width&quot;:1118.53,&quot;height&quot;:1582.7,&quot;fontScale&quot;:1.33}" data-pdf-annotate-document="/uploads/docs/Vishnu/file/IBC-CW1a-DE-02_2.pdf" data-pdf-annotate-page="1" style="width: 1118.53px; height: 1582.7px;">

<circle cx="138.76877404693374" cy="82.72243012162977" r="10" stroke="#000000" fill="#000000" stroke-width="0" data-pdf-annotate-id="b91a7011-656c-48d6-9f1c-62ac4bfc4f91" data-pdf-annotate-type="fillcircle" aria-hidden="true" transform="scale(1.33) rotate(0) translate(0, 0)"></circle>

</svg>


function createCircle(a) {
      var circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
      (0, _setAttributes2.default)(circle, {
        cx: a.cx,
        cy: a.cy,
        r: a.r
        });
        var spot_anchor = document.createElement("a")
        console.log(spot_anchor)
        spot_anchor.appendChild(circle)
        console.log(spot_anchor)

   console.log('Create_circl1')
      return circle;
    }

Как я могу это сделать, используя javascript?

Ответы [ 3 ]

0 голосов
/ 27 апреля 2018

Вашему circle нужно , чтобы быть внутри тега svg, иначе это бессмысленно в вашем html. Поэтому создайте упаковочный SVG так же, как вы делаете circle, затем добавьте circle к этому и svg к вашему anchor:

function createCircle( a ){

  var svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
  var circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
  var anchor = document.createElement( 'a' );

  circle.setAttribute( 'cx', a.cx );
  circle.setAttribute( 'cy', a.cy );
  circle.setAttribute( 'r', a.r );
  
  svg.setAttribute( 'viewBox', `${a.x - a.r} ${a.y - a.r} ${a.r * 2} ${a.r * 2}` );
  svg.setAttribute( 'width', `${a.r * 2}` );
  svg.setAttribute( 'height', `${a.r * 2}` );
  
  svg.appendChild( circle );
  anchor.appendChild( svg );

  return anchor;
  
}

document.body.appendChild( createCircle({ cx: 10, cy: 10, r: 10 }) );

Не следует добавлять такие атрибуты, как fill и stroke, непосредственно к тегу a, поскольку эти атрибуты не поддерживаются и недопустимы. Вы должны использовать data атрибуты в этом случае. Может быть, даже подумайте о том, чтобы просто использовать data-svg-attributes="{'cx':10,'cy':10,'r':10}" и использовать JSON.parse, когда вам нужно получить правильные данные. Обновление : атрибуты fill и stroke будут унаследованы, если вы объявите их в атрибуте style тега переноса, так что вы можете использовать это (иначе style="stroke: red;").

0 голосов
/ 28 апреля 2018

Вы создаете элемент <a> неверным способом. Вы используете:

document.createElement("a")

Это создает элемент <a> в пространстве имен HTML. Другими словами, элемент HTML <a>.

Вам необходимо создать элемент SVG <a>, который будет совершенно другим, даже если он имеет то же имя.

Вы делаете это так же, как вы создали элемент <circle>:

document.createElementNS('http://www.w3.org/2000/svg', 'a');
0 голосов
/ 27 апреля 2018

appendChild, replaceNode и т. Д. Удалит узел из дерева перед его перемещением, поэтому (так как вы неопределенно спросили его, у меня есть 0 идей, существует ли atag или нет, поэтому я предполагаю, что он есть, в противном случае создайте его, используя createElementNS ):

yourSvg = document.querySelector("svg");
    yourCircle = svg.querySelector("circle");
    yourATag = svg.querySelector("a");
    yourATag.appendChild(yourCircle)

Тег не является визуальным элементом, его ограничивающий прямоугольник будет равен тому, что находится внутри. Если вам интересно:

https://jsfiddle.net/ibowankenobi/4t44n8jo/4/

...