How to wrap a set of svg elements with a <g> tag?

How to wrap a set of svg elements with a tag after they are created by javascript (Raphael)?

Or how can I close the g tag after certain elements? When I run the g tag before creating these elements. In this case, g tag starts, but does not end.

Here is my code

+4
source share
4 answers

You cannot wrap a tag around existing elements. A tag has a start and end tag, but there is no such thing as a start element and an end element.

You need to create the g element and move the existing elements to this new element.

0
source

One way is to add the g element and add other elements to it.

 $("path").click(function() { var $svg = $("#mysvg"); // #mysvg is SVG doc var g = document.createElementNS('http://www.w3.org/2000/svg', 'g'); g.setAttribute("id", "g"); $svg.append($(g)); $svg.find("path").each(function() { $(this).css("stroke", "red").appendTo($(g)); }); $("#cont").html($svg); // #cont is svg "container", eg. div }); 

Working example: http://jsbin.com/ayulaq/2

It uses jQuery to simplify DOM operations. I used this method to add all the children in the SVG to the same parent group in order to simplify (and speed up) the determination of the actual frame size for all elements. Sometimes SVG documents do not explain the width and height of the root element of the SVG, or it’s wrong, and to resize the SVG document (or to resize the newly created g-element [and as long as all its children] correspond to the SVG document), we need to get a bbox that covers all the elements. After the above code, we can call $("#g")[0].getBBox() to get the size of all the elements in the SVG document. There is also this way if size matters only: var setti = p.set(); setti.push(path1,path2); console.log(setti.getBBox()); var setti = p.set(); setti.push(path1,path2); console.log(setti.getBBox()); but set not suitable in all cases.

This technology also applies to drag and drop to speed up the drag and drop of large sets of items. Instead of using the Raphael set , which changes the transform attribute of each object in a separate set, using g instead, it’s enough to modify the g attribute to transform the element.

Attention, of course, only refers to the fact that Raphael uses the SVG backend.

+2
source

If you use jQuery, you can use .wrapInner (), which will wrap the contents of the selected element in the tag.

0
source

You have Paper.set () in Raphael. This returns you a group, and you can click directly on this set, and you can do

 group.rotate(45); 

to get the functionality you are looking for.

Link: http://raphaeljs.com/reference.html#Paper.set

-1
source

Source: https://habr.com/ru/post/1401577/


All Articles