简体   繁体   English

如何使用SVG + XML数据设置IMG src?

[英]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. 我有一个函数可以返回由jSignature先前生成并保存到文件中的SVG文件。 My script gets the actual file contents via an ajax call, along with other data about the signature, in a large JSON object. 我的脚本通过ajax调用获取实际文件内容,以及有关签名的其他数据,并在一个大型JSON对象中获取。

This is an offline project, so I'm attempting to store the SVG data in localstorage for rendering while offline. 这是一个离线项目,因此我试图将SVG数据存储在本地存储中,以便在离线时进行渲染。 This is why I can't simply reference the SVG files on the server. 这就是为什么我不能简单地引用服务器上的SVG文件的原因。

I want to assign the SVG image data to an IMG element so the user can see it in the browser. 我想将SVG图像数据分配给IMG元素,以便用户可以在浏览器中看到它。 How can I set this SVG data directly to an IMG tag without needing to write it to a file first? 如何直接将此SVG数据设置为IMG标签,而无需先将其写入文件?

If I try to set the 'src' property, the image shows an invalid image icon. 如果我尝试设置'src'属性,则图像显示无效的图像图标。 I also added the "data:image/svg+xml," text before the actual SVG data but no change. 我还在实际SVG数据之前添加了“ data:image / svg + xml”文本,但没有更改。

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. 我相当确定,如果svg编码为base64,则只能将svg嵌入src中。

You'll probably be better off with a <svg id="image1"></svg> element and using jQuery .replaceWith(..) to swap it out, no? 最好使用<svg id="image1"></svg>元素,并使用jQuery .replaceWith(..)替换掉它,不是吗? (you won't need the xml/doctype gunk). (您不需要xml / doctype gunk)。

Example: JFiddle 示例: JFiddle

HTML 的HTML

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

Javascript Java脚本

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') );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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