Linear gradient not applying in Webkit with d3 generated SVG - svg

I'm creating a specific implementation for a d3.js graph, and it seems that when creating an SVG document dynamically, linearGradients are not working on Webkit browsers (tested only on Chrome, of the Webkit family), while Gecko is showing the expected behavior.
How do I conclude it has to do with dynamic generation, or d3? I tried copying the resulted document into an empty page, and the gradient came to life.
The d3 code initializes the document first:
// in construction:
// ...
svg = d3.select(el)
.append('svg:svg')
.attr('width', width)
.attr('height', height),
defs = svg.append('svg:defs'),
linearGradient1 = defs.append('svg:linearGradient')
.attr('id', 'linear-gradient-1')
.attr('x1', 0)
.attr('y1', 1)
.attr('x2', 6.123233995736766e-17)
.attr('y2', 0),
linearGradient1Stop1 = linearGradient1.append('svg:stop')
.attr('offset', '0%')
.attr('stop-color', '#e3e5e8'),
// several other stops here ...
… than refreshes the renderer, e.g. after adding "nodes" to the graph data struct, on demand (note: selfRef.node is simply a handle to the d3 selector of all the nodes):
// called e.g. when adding new nodes:
refresh: function() {
// ...
// add new nodes
var g = selfRef.node.enter().append('svg:g').attr('class', 'node');
g.append('svg:rect')
.attr('width', 144)
.attr('height', 42)
.attr('rx', 3)
.attr('ry', 3)
.attr('fill', 'url(#linear-gradient-1)')
.style('stroke', '#4d4d4d')
.style('stroke-width', 1)
// ...
}
Here's the generated document, it's nothing special:
<svg width="1889" height="400">
<defs>
<linearGradient id="linear-gradient-1" x1="0" y1="1" x2="6.123233995736766e-17" y2="0">
<stop offset="0%" stop-color="#e3e5e8"></stop>
<stop offset="11%" stop-color="#e6e8ec"></stop>
<stop offset="59%" stop-color="#eff2fa"></stop>
<stop offset="100%" stop-opacity="0.6" stop-color="#f2f6ff"></stop>
</linearGradient>
</defs>
<g>
<g class="node"
transform="translate(1113.425033222223,312.1412317958371)">
<rect width="144" height="42" rx="3" ry="3"
fill="url(#linear-gradient-1)"
style="stroke: #4d4d4d; stroke-width: 1px;"></rect>
<!-- some other shapes of the node... -->
</g>
<!-- etc. etc., some more node groups here... -->
</g>
</svg>
Things I have tried
Pulling the element referencing the gradient outside any group.
Adding version declaration to the SVG with varying values (maybe it only appears on 1.1?)
Wrapping the reference in quotes (i.e. fill="url('#linear-gradient-1')") or omitting the dashes from the id, thinking Webkit is less lenient here.
Note
Robert Longson mentioned that case matters in this post, and, weird enough, it seems that when pasting the document in an empty page (in the Chrome's dev-tools), the linear gradient element transforms to camel-case format (though it doesn't show in the DOM view, all is lowercase there). I discovered this after diffing the results of my d3 generated code and the pasted static document. What's up with that?
TL;DR
How come generating dynamic SVG gradients don't work when running in Chrome, and how to fix this?

Seems like the Safari developers marked the bug as works for me, based on it working in xhtml. For Safari it seems you'd have to serve your webpages with a mime type of application/xhtml+xml or petition the Safari developers to reopen the bug. FWIW it seems like a bug to me.

Related

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?
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/

Bind external svg to data

Community,
I would like to bind an external svg file to my data-array.
I loaded the element into my dom like this:
defs = d3.select("defs");
d3.html("combisymbol.svg", function(data) {
//get a selection of the image so we can pull out the icon
xml = d3.select(data);
icon = document.importNode(xml.select("#star").node(), true);
icon.id = "staricon";
defs.node().appendChild(icon);
// console.log("icon", icon);
Then I tried to make it visible. I used the same approach as when I take circles that I bind to my data. With the circles it works, but my external svg is not visible.
d3.select("body").select("div#divCombiSVG")
.selectAll("star")
.data(combiData)
.enter()
.append("svg:use")
.attr("xlink:href", "#staricon");
I don't see the svgs.
I have also tried this:
d3.select("body").select("div#divCombiSVG")
.selectAll("star")
.data(combiData)
.enter()
.append("svg")
.attr("width",200)
.attr("height",200)
.node().appendChild(icon);
But then the icon gets only added to the first data-element and not the second. Even though it's added to the first, it's still not visible.
The svg file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904 /DTD/svg10.dtd">
<svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="200px" height="200px" viewBox="0 0 37.207 100" enable-background="new 0 0 37.207 100"
xml:space="preserve">
<path xmlns="http://www.w3.org/2000/svg" id="star" cx="50" cy="50" r="20" r2="43"
orient='point' points='3' radial-shift='0' outerCurve='86'
outerOffset='4.1' innerCurve='56' innerOffset='2.2' d="M300,168
C347.7790400396858,178.49361334198113
345.7070270919484,217.64466544113793 337.23909236273084,228.5
C350.87405522189334,226.59422068634012 385.8158673985199,244.3753308862077 371.014083110324,291
C338.0368273588341,327.1310557718112
305.1670281299449,305.76111387252195 300,293 C294.83297187005513,305.76111387252195
261.9631726411659,327.1310557718112 228.98591688967605,291 C214.1841326014801,244.37533088620776
249.12594477810666,226.59422068634015 262.7609076372691,228.50000000000003
C254.29297290805158,217.64466544113793 252.22095996031422,178.4936133419811 300,168 "
fill="yellow" stroke="black" stroke-width="2"></path>
</svg>
combiData currently has two objects.
I have looked for hours at other examples but I can't make it work. I think I'm close though...I'm pretty new to d3 (but very motivated) so please be patient with me. :-)
Thanks in advance for your help!
In the first case, you are doing a .selectAll('star') (searching for the tag star), which probably should have been a .selectAll('#star') (searching for a tag with id star).
Your second approach can be tweaked a little to work as well. Calling node() on a d3 selection always returns just one node. Hence, the subsequent .appendChild happens only on the first node.
You can try this, if you find this more amenable to what you wanted to do:
d3.select("body").select("div#divCombiSVG")
.selectAll("star")
.data(combiData)
.enter()
.append("svg")
.attr("width",200)
.attr("height",200)
.each(function (d) {
this.appendChild(icon);
});
Since in the comments you asked for which option to prefer: I would recommend the first approach of using the use element. It results in less code and you can even refer to the file containing the star externally which means that you will not have to download and inline the SVG yourself (note the caveat about IE).

SVG (1.1) : how to 'link-to' or 'centre' on a shape in a browser?

Is there is browser-independant way getting the browser to centre on a particular shape (by 'id' attribute) ?
I have tried using xlinks wrapped around shapes like this:
<a xlink:href="#node24"> .... </a>
I have reasonably busy (100+ shapes) directed graph diagrams (generated from dot): and when I load them up in Chrome , more often than not, the intial screen is just blank - forcing the user to use scrollbars to find the diagram at all.
I'm afraid I don't have any good news for you.
For stand-alone SVG documents, you can manipulate the part of an SVG displayed when following a link by linking to a <view> element (distinct from, but making use of, the SVG "viewBox" attribute). The view element specifies the viewBox to use and possibly some other parameters, and the graphic will be displayed with those parameters instead of the default ones.
Example code:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 100 100"
preserveAspectRatio="xMidYMin meet" >
<circle cx ="50" r="40"/>
<view id="panUp" viewBox="0 -50 100 100" />
<view id="zoomIn" viewBox="25 25 50 50" />
</svg>
If you linked to the file as a whole it would show you an image with half a circle centered at the top of the screen.
If, however, you linked to it like http://example.com/sample.svg#panUp, the circle would be the same size but centered on screen. If you linked to http://example.com/sample.svg#zoomIn, you'd only see the bottom edge of a circle that is twice as big.
(I don't have anywhere to host the file that can serve up raw SVG files, but this CodePen uses data URI to show the effects, although the data URI fragment identifiers doesn't seem to work in Firefox.)
You are supposed to be able to even specify the desired viewBox, transforms, or other attributes as part of the URL fragment (like http://example.com/sample.svg#myView(viewBox(0,0,200,200))), but I don't think that's widely implemented -- it had no effect on either Firefox or Chrome.
And even <view> fragments don't seem to work when the SVG is embedded within an HTML document. So unless your SVG is stand-alone, creating a view for each element (or one view that your dynamically change to match the clicked element), isn't going to be worth the trouble.
So what does work?
The default behaviour, when linking to a fragment (element id) that is not a <view> is to display the nearest ancestor <svg> element that contains that element ("nearest ancestor" because an SVG can contain nested <svg> tags). So if your document has a natural structure to it, you could replace some <g> elements with <svg> with a specified x,y,height and width parameter, and then linking to an element within that sub-graphic would show that view. That should work even when the SVG is embedded within a larger HTML document. But if you've got hundreds of elements moving around, it's probably not a practical solution.
Which leaves #Ian's solution of programmatically manipulating the main SVG viewBox. If you don't want to zoom in, just pan, leave the width and height as the full size of your visualization, and just change the x and y offsets. Something like:
function centerViewOnElement( el ) {
var bbox = el.getBBox()
var elCenterX = bbox.x + bbox.width/2,
elCenterY = bbox.y + bbox.height/2;
svg.setAttribute("viewBox", [(elCenterX - width/2),
(elCenterY - height/2),
width,
height
].join(" ") );
//assuming you've got the svg, width and height already saved in variables...
}
Thought I would do a simpler example, as this feels quite useful in general...with a jsfiddle here
<svg id="mySvg">
<circle id="myCirc" cx="20" cy="20" r="20"/>
<rect id="myRect" x="50" y="50" width="50" height="50"/>
</svg>
var mySvg = document.getElementById("mySvg");
function getNewViewbox( el ) {
var bbox = el.getBBox();
return newViewbox = bbox.x + " " + bbox.y + " " + bbox.width + " " + bbox.height;
}
function focusElement( ev ) {
ev.stopPropagation();
mySvg.setAttribute("viewBox", getNewViewbox( ev.target ) );
}
//click on any element, or even the svg paper
document.getElementById("mySvg").addEventListener("click", focusElement);

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