Get attributes of use element that are defined by defs element with snap.svg - 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?

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/

Related

Snap.svg inner shadow on animated arc

I just starting working with svgs and Snap.svg library. Following a tutorial I created an arc progress indicator. What I want now is to add an inner shadow to the animated arc. I read the documentation but the filter.shadow command only gives the option for an outer shadow. I did some research on adding filters to regular svgs and I added one to the svg that I'm binding to my Snap object. It does give me the inner shadow, however it ruins the arc animation; only about half of the arc appears even though the inner shadow is present. I changed some of the filter settings trying to fix it but nothing works. I'm thinking that filter only works for static svgs.
Any help would be appreciated. Thanx
UPDATE
Here is the code that I'm using.
<svg class="gauge" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px" y="0px" viewBox="0 0 400 200" xml:space="preserve">
<path fill="none" stroke="#D1D2D1" stroke-miterlimit="10" d="M199.7,12.7V18h0.4v-5.3H199.7z M382,200c0-50-20.3-95.4-53.1-128.4
l8.4-8.4l-0.4-0.4l-8.4,8.4C295.6,38.4,250.1,18,200,18S104.5,38.3,71.5,71.2l-8.3-8.3l-0.4,0.4l8.3,8.3C38.3,104.5,18,149.9,18,200
h44c0-38,15.4-72.4,40.3-97.4l7.5,7.5l0.4-0.4l-7.5-7.5c24.9-24.8,59.2-40.2,97.1-40.3v10.5h0.5V62c38.1,0.1,72.6,15.6,97.5,40.7
c-0.1-0.1-0.2-0.2-0.3-0.4l-7.4,7.4l0.4,0.4l7.4-7.4c24.8,25,40.2,59.4,40.2,97.3H382z M102.3,102.6l0.3-0.3L102.3,102.6z"/>
</svg>
<script type="text/javascript">
var canvasSize = 400,
centre = canvasSize/2,
radius = canvasSize*0.8/2,
s = Snap('.gauge'),
path = "",
startY = centre-radius,
arc = s.path(path);
function fill(percent) {
var endpoint = percent*180;
Snap.animate(0, endpoint, function (val) {
arc.remove();
var d = val,
dr = d-180;
radians = Math.PI*(dr)/180,
endx = centre + radius*Math.cos(radians),
endy = centre + radius * Math.sin(radians),
largeArc = d>180 ? 1 : 0;
path = "M"+startY+","+centre+" A"+radius+","+radius+" 0 "+largeArc+",1 "+endx+","+endy;
arc = s.path(path);
arc.attr({
stroke: '#fff',
fill: 'none',
strokeWidth: 44,
});
}, 1500, mina.backout);
}
fill(50/100);
</script>
I added this code to the attribute to get an outer shadow.
arc.attr({
filter : s.filter(Snap.filter.shadow(1, 1, 2, 'black', 0.5))
})
I was wondering if there's something similar for an inner shadow.
I also tried adding this to the the embedded svg and then adding the attribute to the animated arc thinking it might work like a regular, static svg. It does give me an inner shadow, however only part of the animated arc gets displayed; it gets displayed within a rectangle.
<defs>
<filter id="inner-shadow">
<feGaussianBlur result="offset-blur" stdDeviation="5"></feGaussianBlur>
<feOffset dx="1" dy="1"></feOffset>
<feFlood flood-color="black" flood-opacity="1" result="color"></feFlood>
<feComposite operator="in" in2="offset-blur"></feComposite>
<feComponentTransfer>
<feFuncA slope="0.5"></feFuncA>
</feComponentTransfer>
<feMerge>
<feMergeNode></feMergeNode>
<feMergeNode in="SourceGraphic"></feMergeNode>
</feMerge>
</filter>
</defs>
arc.attr({
stroke: '#fff',
fill: 'none',
strokeWidth: 44,
filter: 'url(#inner-shadow)',
});
You can adjust the filter area that its applied over so that it doesn't get cut off. The Snap code seemed to give an error for me, so I just tried it using the svg filter markup, as the problem seems to be SVG related, rather than Snap.
So the key bit to change would be..
<filter id="inner-shadow" y="-30" x="-30" height="400" width="500">
This gives an offset wider range. You can read more on that at filter docs
jsfiddle

Wrap text inside SVG rectangle. I want to resize the svg rectangle when user tries to enter the text continuously

I want something like below. Initially there will be a single word when user enters multiple words the size of the box increases. How can I achieve this? Anyone have any idea as to how to proceed on this ?
You can compute the length of the text using http://www.w3.org/TR/SVG/text.html#__svg__SVGTextContentElement__getComputedTextLength
and then you can resize the rect that depends on the textLength. You can call resize function when onkeydown event fires.
Here is an example of resizing the rect when the text length is changed by interval.
<svg id="svg" xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect width="100" height="100" style="fill:rgb(255,255,255);stroke-width:3;stroke:rgb(0,0,0)" ></rect>
<text x="20" y="40">123</text>
</svg>
<script>
var textElement = document.getElementsByTagName('text')[0];
var rectElement = document.getElementsByTagName('rect')[0];
resizeRect();
setInterval(resizeRect, 1000);
function resizeRect(){
textElement.textContent += 0
var textLength = textElement.getComputedTextLength();
rectElement.setAttribute("width", 50 + textLength)
}
</script>
You can find a fiddle here: https://jsfiddle.net/0dvu604g/

SVG: Dragging objects between two different SVG elements

I'm developing a prototype to mock this tool and provide minimal functionality like
Drag-n-Drop simple objects
Connect related objects via paths
Generate JSON from this structure
I opted SVG and Snap.svg framework (had hard time in deciding between D3 and Snap.svg but ended up with latter just because it is latest and successor of Raphael) to implement it. I stuck with below during implementation
Question 1: How to drag objects between different SVG elements? Try dragging elements in this Fiddle, objects were hidden when dragged outside of its parent dimension. Fiddle snippet below for your perusal.
HTML/SVG:
<div class="stencil">
<svg id="stencil" height="300" version="1.1" width="120" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>
</div>
<div class="paper">
<div class="paper__scroller">
<svg id="paper" height="1000" version="1.1" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>
</div>
</div>
Javascript:
(function(){
var pap = Snap("#paper"),
stencil = Snap("#stencil"),
cir = stencil.circle(30, 50, 20),
rec = stencil.rect(70, 33, 35, 35);
stencilElements = stencil.group(rec, cir);
stencilElements.attr({
fill: "#f00",
stroke: "#000",
strokeWidth: 2,
"fill-opacity": 0.5
});
cir.clone().drag();
rec.clone().drag();
}());
Question 2: How to connect related objects via paths that adjust/moves accordingly when the object is dragged?
Question 3: How to convert the generated graph/diagram to JSON structure?
Really appreciate any reference or hints in implementing this.

Half filled circle with d3.js

I am trying to create a half filled circle with d3.js to be like this.
I didn't find any example of how to do it.
How can this be done with d3.js?
Yes, you can do that with an SVG gradient. All you have to do is define it and then use it as fill for the circle.
var grad = svg.append("defs").append("linearGradient").attr("id", "grad")
.attr("x1", "0%").attr("x2", "0%").attr("y1", "100%").attr("y2", "0%");
grad.append("stop").attr("offset", "50%").style("stop-color", "lightblue");
grad.append("stop").attr("offset", "50%").style("stop-color", "white");
svg.append("circle")
.attr("fill", "url(#grad)");
JSfiddle here.
You may not even require d3 for this simple task. You may use this simple technique, Using Clippath on a circle, I have written it in details in my blog http://anilmaharjan.com.np/blog/2013/11/create-filled-circle-to-visualize-data-using-svg
Use Two circles one above another in a tag.
Fill one with the color you wish and another with white or may be your background color just to make it look like its empty in there.
Then clip the later one using with rectangle in it, assign radius few pixel less than the earlier circle.
Place clip path at the top left .. assign width equal to the diameter of the circle and height will be defined by your data.
The data will act reversible to the filling so you may subtract the actual data from your max. EG: if data is 20/100 do 100-20 so u ll get 80 in this way the empty part will be 80 and filled will be 20.
You may switch between height or width to switch between vertical or horizontal filling axis.
The HTML should look like this.
<svg height="200"> <a transform="translate(100,100)">
<g>
<circle fill="#f60" r="50"></circle>
</g>
<g>
<clippath id="g-clip">
<rect height="50" id="g-clip-rect" width="100" x="-50" y="-50">
</rect>
</clippath>
<circle clip-path="url(#g-clip)" fill="#fff" r="47"></circle>
</g>
</a>
</svg>
I have created a jsfiddle to illustrate this at: http://jsfiddle.net/neqeT/2/
create a div having id name id_cirlce and paste this code inside script tag
<div id="id_circle"></div>
<script>
var svg = d3.select("#id_circle")
.append("svg")
.attr("width",250)
.attr("height",250);
var grad = svg.append("defs")
.append("linearGradient").attr("id", "grad")
.attr("x1", "0%").attr("x2", "0%").attr("y1", "100%").attr("y2", "0%");
grad.append("stop").attr("offset", "50%").style("stop-color", "lightblue");
grad.append("stop").attr("offset", "50%").style("stop-color", "white");
svg.append("circle")
.attr("r",50)
.attr("cx",60)
.attr("cy",60)
.style("stroke","black")
.style("fill","url(#grad)");
</script>

SVG translate with em as unit?

Is there a way to use em as unit for SVG translations? As in
<rect height="10em" width="10em" transform="translate(0em, 10em)"
style="fill:none;stroke-width:3;stroke:black/>
The rectangle does not translate in Firefox, unless I remove the em as unit.
You can sort of do this if you wrap the element(s) you want to translate in a new coordinate system:
<svg>
<svg width="1em" height="1em" overflow="visible" viewBox="0 0 1 1">
<rect height="10" width="10" transform="translate(0, 10)" .../>
</svg>
</svg>
Another option if you only need translations and use elements that have x and y attributes (or equivalent) is to use those instead, like this:
<rect x="0" y="10em" height="10em" width="10em"
style="fill:none;stroke-width:3;stroke:black/>
A new specification for transforms in CSS/SVG is currently being worked on, and it will indeed allow units in translations, see here.
Unfortunately, not;
The specs explicitly allow for user units - that correspond to CSS units and default to pixel units when otherwise not specified - to be applied for coordinates, while translations are meant to be used with floating point numbers exclusively as defined by the SVGMatrix interface.
Another thing you could do if you're creating the rect with javascript is retrieve the font size of a parent element and convert the em value to px.
Using jQuery:
var one_em = +$("#parent").css("font-size").replace("px", "");
$("#parent").append("<rect transform=translate(0," + (10*one_em) + ") .../>")

Resources