简体   繁体   中英

How to set an IMG src with SVG+XML data?

I have a function that returns an SVG file that was earlier generated by jSignature and saved into a file. My script gets the actual file contents via an ajax call, along with other data about the signature, in a large JSON object.

This is an offline project, so I'm attempting to store the SVG data in localstorage for rendering while offline. This is why I can't simply reference the SVG files on the server.

I want to assign the SVG image data to an IMG element so the user can see it in the browser. How can I set this SVG data directly to an IMG tag without needing to write it to a file first?

If I try to set the 'src' property, the image shows an invalid image icon. I also added the "data:image/svg+xml," text before the actual SVG data but no change.

Here's an example:

// This would be read from localStorage:
var image_data = '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"1000\" height=\"151\"><path />...snipped...</svg>';

// Show the SVG image:
$("#image1").attr('src', 'data:image/svg+xml,' + image_data);

However, this doesn't work. What am I doing wrong?

I'm fairly sure that you can only embed svg in a src like that if the svg is encoded to base64.

You'll probably be better off with a <svg id="image1"></svg> element and using jQuery .replaceWith(..) to swap it out, no? (you won't need the xml/doctype gunk).

Example: JFiddle

HTML

<svg id="image1"></svg>

Javascript

var imageData = '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>';
$('#image1').replaceWith( $('<div/>').append(imageData).find('svg:first').attr('id','image1') );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM