Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use javascript to insert an svg use element into an svg group?

I have an svg file containing a group with a single line element. I can make use of the use element and make several reference copies in any position I want them. However, I want to use javascript to add and remove the use element dynamically. Is there a way to use javascript to insert an svg use element of my line into my group?

<svg version="1.1" id="ex1-3rds-quarter-s" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
 y="0px" width="323.333px" height="55.333px" viewBox="0 0 323.333 55.333" enable-background="new 0 0 323.333 55.333"
 xml:space="preserve">
<g id="ledgerlines">
  <line id="MidCLine1" fill="none" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" x1="48.09" y1="41.694" x2="57.924" y2="41.694"/>
</g>
</svg>
like image 543
Christopher Gaston Avatar asked May 05 '14 00:05

Christopher Gaston


People also ask

Can JavaScript be applied to SVG?

Since SVG images can be inlined in HTML, we can manipulate them with JavaScript. This means that we can animate parts of an image from code, make it interactive, or turn things around and generate graphics from data. In this example, we are going to create a watch.

Does Z Index work with SVG?

Contrary to the rules in CSS 2.1, the z-index property applies to all SVG elements regardless of the value of the position property, with one exception: as for boxes in CSS 2.1, outer 'svg' elements must be positioned for z-index to apply to them.

How do you interact with SVG?

svg is a markup language, meaning that you can use css selector libraries such as jquery to interact with the given svg. You can query the svg in order to get an element by its id, or get an array of elements selected by class. You can attach event handlers to them such as click , mouseover , mouseenter , etc.

What is the G element in SVG?

The <g> SVG element is a container used to group other SVG elements. Transformations applied to the <g> element are performed on its child elements, and its attributes are inherited by its children. It can also group multiple elements to be referenced later with the <use> element.


1 Answers

var  svgns = "http://www.w3.org/2000/svg";
var  xlinkns = "http://www.w3.org/1999/xlink";

// Get a reference to the <g> element    
var  g = document.getElementById("ledgerlines");

// Create a <use> element
var  use = document.createElementNS(svgns, "use");
// Add an 'href' attribute (using the "xlink" namespace)
use.setAttributeNS(xlinkns, "href", "#MidCLine1");
// Offset the line down by 10
use.setAttribute("y", "10");  // offset = y+10

// Add the <use> to the <g>
g.appendChild(use);

Demo here

like image 184
Paul LeBeau Avatar answered Nov 15 '22 20:11

Paul LeBeau