xr280xr
xr280xr

Reputation: 13302

Get attributes of use element that are defined by defs element with snap.svg

I'm new to svgs and brand new to snap.svg. I'm working on generating elements within an SVG and have the following to work with:

<svg width="600" height="400" style="shape-rendering: geometricPrecision; position: absolute;
        left: 0; top: 0;">
        <defs>
            ...
            <circle id="dot" r="10" stroke-width="2"></circle>
        </defs>
    </svg>

I want to use javascript to create mutliple instances of the circle #dot at different positions. So I have some javascript using snap.svg like this:

var dot = svg.use("dot");
var r = dot.attr("r");
dot.attr({ x: shapeData.X-r, y: shapeData.Y-r, class: "dot" });

but the value I'm getting for the radius, r, is null. How can I access values describing my circle like, r, width, height, fill color, etc?

Upvotes: 1

Views: 2277

Answers (1)

AustinC
AustinC

Reputation: 826

The way use elements work in SVG is they are basically just pointers to the original object. If you place a clone of that dot on the canvas with use, the clone doesn't have a defined radius. It points back to dot, which has a defined radius.

It's not entirely clear to me what all you need to do but I think the right way to approach this is to get a reference to dot that you can then use for this purpose. You can clone dot and add other attributes to it later.

Aside from that you're just missing a lot of Snap stuff you need but maybe that's because you're just giving us a snippet.

Here's some code:

<svg id="svg" width="600" height="400" style="shape-rendering: geometricPrecision; position:absolute;left: 0; top: 0;">
<defs>
  <circle id="dot" r="10" stroke-width="2"></circle>
</defs>
</svg>

JS:

// reference to svg
var svg=Snap('#svg')

// reference to dot, stored in a
var a=svg.select('[id="dot"]')

// what's the radius of a?
var r=a.attr('r')
alert('The radius is '+r)

// clone a and add it to the svg
b=a.use()
svg.append(b)

// give b some attributes
b.attr({x:100,y:50})
console.log(b.attr())

Fiddle here: https://jsfiddle.net/ksy7mLsx/1/

Upvotes: 3

Related Questions