I have trouble composing an inline-SVG using Javascript.
The problem can be reduced to the following code (live example here):
Somewhere inside the body:
<svg id="drawing" xmlns="http://www.w3.org/2000/svg" version="1.1">
</svg>
Inside onReady:
$("#drawing").append($("<rect style='fill: blue' width='100' height='100' />"));
I expected to see a blue rectangle now. However, Chrome and Firefox don't show anything.
Using Firebug, I found out that Firefox interprets the "rect" as a HTMLUnknownElement (and not as a SVGElement).
If I choose "Edit SVG" on the SVG element (using Firebug) and insert a whitespace somewhere, the SVG seems to be reparsed and the rectangle appears.
How can I tell the parser to parse this fragment correctly?
I'm afraid it's not that easy:
jsfiddle is not the place to test svg, it sends wrong content-type
references to external js-files can't be created the html-way(always keep in mind, svg doesn't have to do anything with html)
jquery uses some dummy-div's for creating the elements when using append(), but svg doesn't know div-elements
also note: binding's to the load-event of a svg-document with jQuery doesn't seem to work
Here an example-code, works for me in FF when delivered as image/svg+xml
<svg id="drawing"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1"
onload="fx()">
<script type="text/ecmascript" xlink:href="http://code.jquery.com/jquery-latest.js" />
<script type="text/ecmascript">
function fx()
{
$(document.createElementNS('http://www.w3.org/2000/svg', 'rect'))
.css('fill','blue')
.attr({'width':100,'height':100})
.appendTo('#drawing');
}
</script>
</svg>
But like Marcin I would suggest to use a plugin.
To add from the parent document you may use an object containing the properties of the element, basic example:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
function fx(obj,params)
{
var svgDoc=obj.contentDocument;
if(typeof params.name!='string')return;
var props=$.extend({'attrs':{},'style':{},'selector':null},params);
props.target=(!props.selector)?svgDoc.documentElement:$(svgDoc).find(props.selector)
$(svgDoc.createElementNS('http://www.w3.org/2000/svg', props.name))
.css(props.style)
.attr(props.attrs)
.appendTo(props.target);
}
/*]]>*/
</script>
</head>
<body>
<object onload="fx(this,{'name':'rect','attrs':{'width':100,'height':100},'style':{'fill':'blue'},'selector':'#drawing'})"
data="my.svg"
type="image/svg+xml"
width="200"
height="200">
<param name="src" value="my.svg">
</object>
</body>
</html>
The structure of the object:
name:tagName(string)
attrs:attributes(object)
style:style(object)
selector:selector(string, if omitted the root-element will be selected)
This example shows how to embed SVG in XHTML, including the programmatic creation of new SVG elements: http://phrogz.net/svg/svg_in_xhtml5.xhtml
This example shows how to use XHR to fetch SVG as XML, find a fragment of it, and two ways convert it into the local document before appending the node to the existing SVG document: http://phrogz.net/svg/fetch_fragment.svg
In general:
Don't use jQuery with SVG directly.
Dynamically-created SVG elements must be created using createElementNS, supplying the SVG namespace URI 'http://www.w3.org/2000/svg'. (Note, however, that the SVG attributes should not be created with a namespace.)
You need to be sure to serve your XHTML as XML (content-type: application/xhtml+xml) and not as text/html.
Here's a general-purpose function I use on occasion for creating SVG elements conveniently. It works both within SVG documents as well as SVG-in-XHTML, allows for text content to be created directly, and supports namespaced attributes (such as xlink:href).
// Example usage:
// var parentNode = findElementInTheSVGDocument();
// var r = createOn( parentNode, 'rect', {
// x:12, width:10, height:10, 'fill-opacity':0.3
// });
function createOn(root,name,attrs,text){
var doc = root.ownerDocument;
var svg = root;
while (svg.tagName!='svg') svg=svg.parentNode;
var svgNS = svg.getAttribute('xmlns');
var el = doc.createElementNS(svgNS,name);
for (var attr in attrs){
if (attrs.hasOwnProperty(attr)){
var parts = attr.split(':');
if (parts[1]) el.setAttributeNS(svg.getAttribute('xmlns:'+parts[0]),parts[1],attrs[attr]);
else el.setAttributeNS(null,attr,attrs[attr]);
}
}
if (text) el.appendChild(document.createTextNode(text));
return root.appendChild(el);
}
I assume you'd like to get a fragment of SVG parsed, without having to turn it into JSON and whatnot. Here's some CoffeeScript that does it. I tested the code on SVG embedded in HTML, but I think it should work in any circumstance.
https://github.com/pwnall/ddr/blob/master/javascripts/graphics/pwnvg.coffee#L169
I wrap the SVG fragment in an tag to build a stand-alone SVG document, then I use a DOMParser to parse the SVG document, and I pull out the children of the root element (the wrapper) one by one, and stick them into the original SVG's DOM.
In theory, there is an easier (and faster approach), but it doesn't work right now. http://crbug.com/107982
See: Convert svg into base64
I always make sure a svg fragment is inside a svg element or just force refresh the svg.
Related
I have an svg uploaded to my website and I want to embed it into my html so that it can have the structure of svg and path:
<svg>
<path id="svgPath"/>
</svg>
I managed to do it with image
<svg width="1920" height"720">
<image id="imgId" xlink:href="srclink" width="1920" height="720" />
</svg>
And when I query that image, I don't have the same methods that I have as for a path element. For example, I don't have the .getTotalLength()
const path = document.querySelector("#pathId");
path.getTotalLength(); // will work
const img = document.querySelector("#imgId");
img.getTotallength(); // does not work
I can insert it with Javascript too, if there is a way to do that while loading it from the srclink.
I need to be able to access the path as the rest of my code is dependent on that.
If it is an external *.svg file, A native Web Component <load-file> can fetch it and inject it in the DOM; either in shadowDOM or replacing the <load-file> Element, thus becoming part of the DOM you can access and style with CSS.
customElements.define("load-file", class extends HTMLElement {
// declare default connectedCallback as sync so await can be used
async connectedCallback(
// call connectedCallback with parameter to *replace* SVG (of <load-file> persists)
src = this.getAttribute("src"),
// attach a shadowRoot if none exists (prevents displaying error when moving Nodes)
shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
) {
// load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
shadowRoot.innerHTML = await (await fetch(src)).text()
// append optional <tag [shadowRoot]> Elements from inside <load-svg> after parsed <svg>
shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))
// if "replaceWith" attribute
// then replace <load-svg> with loaded content <load-svg>
// childNodes instead of children to include #textNodes also
this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
}
})
Full explanation in Dev.To post: 〈load-file〉Web Component, add external content to the DOM
Upon trying to import an SVG into the paper.js canvas, the element logs as "null".
<script src="path/to/paper-full.min.js"></script>
<canvas id="myCanvas" resize></canvas>
<script src="path/to/script.js" type="text/paperscript" canvas="myCanvas"></script>
inside script.js:
var svg = '../assets/couch.svg';
var couch = project.importSVG(svg);
console.log(couch); // returns null
I don't know why this isn't working, as this method seems to be used in solutions to different answers… -> Import svg with gradient stroke to paper.js project
Expected output of console.log would be an object (see http://paperjs.org/reference/item/#importsvg-svg where it says "Returns:
Item — the newly created Paper.js item containing the converted SVG content")
right, it appears that you can only import and work with SVG files from the importSVG() callback. If you want to use it as an object outside the callback function, it needs to be a DOM element.
copy and paste the content of the SVG file "inline" into your html file, append it using the fetch API or echo its contents from the backend (which is what I ended up doing), then:
svg = document.getElementById('your-selector')
var yourConvertedSVGItem = project.importSVG(svg, function() {
svg.style.display = 'none' // hide the source image or do something else here
})
console.log(yourConvertedSVGItem)
I have made an SVG image of a Cat in Illustrator. I have named my layers so I have my cats eyes named "eyes".
When I import the SVG to a developer window I can see that the layer name is there
<g id="eyes">
<path class="cls-1" d="M.25,766.38c2.52,9,16.26,23.83,35.15,39.06s3
...
Now via JavaScript I would like to change the color to eyes. How do I do that?
HTML:
<object id="bild" data="a.svg" type="image/svg+xml"></object>
JavaScript:
var catImage = document.getElementById( 'bild');
catImage.layerName.style="fill:red";
A SVG imported inside a <object> or <img> tag cannot be directly styled by the css or the javascript of the host page.
However, for <object>, you can gain such access thru the contentDocument property of the objectelement.
In your case, that would be ...
let cat = document.getElementById('bild').contentDocument;
But, the contentDocument property will not be available until after the page has been completely loaded and rendered. So, you will need to put your code inside an on-load event handler.
Which, in your case, that would be ...
window.addEventListener("load", function() {
let cat = document.getElementById('bild').contentDocument;
let eyes = cat.getElementById('eyes');
eyes.style.fill="red";
});
I have a page where i open a modal and i want that each time it is opened a new svg image is displayed there.
<div class="col s3 center-align" id="event_logo">
<object type="image/svg+xml" data="" id="literary_logo_object" class="event_logo_object" ></object>
</div>
I want to assign the data attribute of <object> dynamically.
What i tried is
document.getElementById('literary_logo_object').setAttribute('data','svg/literary.svg');
var event_logo = Snap(Snap("#literary_logo_object").node);
It seems that changing the attribute data is not allowed like this. After adding the last line, i get the following error
Error: Invalid value for <svg> attribute height="undefined"
Error: Invalid value for <svg> attribute width="undefined"
both the errors are in line 930 of snap.svg.js, which is very highly unlikely.
What else i have tried
I readily defined the object tag like this
<div class="col s3 center-align" id="event_logo">
<object type="image/svg+xml" data="svg/literary.svg" id="literary_logo_object" class="event_logo_object" ></object>
</div>
and made it hide, i.e., display : none
then i tried unhiding the object like
$("#literary_logo_object").show();
var event_logo = Snap("#literary_logo_object").node;
again after the second line i am getting the same error.
Its not quite clear what you are attempting, ie I'm not sure why you are using Snap (yet) for this.
document.getElementById('literary_logo_object').setAttribute('data','svg/literary.svg');
The above should load the new svg in place, thats it.
You don't need Snap for this, as you aren't doing anything with the svg.
I'm also not sure why you don't just use a Snap.load() function, or is there some specific reason you need an object tag ?
If you want to then do something with the SVG thats loaded, you can reference it with 'contentDocument' (as this is in a different document), so using Snap it would look something like this...
var obj = document.getElementById('literary_logo_object');
obj.setAttribute('data','svg/literary.svg');
obj.onload = function( ev ) { // it may take a while to load
Snap( obj.contentDocument.getElementById("someElInsideSvg") )
.animate({ transform: 't-400,-400' }, 2000); //do whatever
}
I have an element (in html)
<image xlink:url="https://abc" id="my_ele">
I do
ele = document.getElementById("my_ele")
// Now want to get https://abc
This answer here Getting 'xlink:href' attribute of the SVG <image> element dynamically using JS in HTML DOM
says:
getAttributeNS('http://www.w3.org/1999/xlink', 'href');
But I'm not really sure what that translates to in my example.
(btw, Google docs displays images like this, at least in Chrome. Don't know why they don't use a proper IMG tag.)
<image xlink:href="https://abc" id="my_ele">
and
ele = document.getElementById("my_ele")
var url = ele.getAttributeNS('http://www.w3.org/1999/xlink', 'href');