[英]How to get svg icon as a string from a .svg file
Is there a way to get svg icon as a string while you have the .svg
file with JavaScript ?当您拥有带有 JavaScript 的
.svg
文件时,有没有办法将 svg 图标作为字符串?
To be more clear, I need a function which does:为了更清楚,我需要一个函数:
function svgFileToString('./icon.svg'){
...
...
return `<svg>...</svg>`
}
You can use the fetch() function.您可以使用fetch()函数。 The function
svgFileToString()
will not return anything, but you can replace console.log(text);
函数
svgFileToString()
不会返回任何内容,但您可以替换console.log(text);
with whatever.随便什么。
For the example I'm using a data URL to replace the real path to a file.例如,我使用数据 URL 替换文件的真实路径。
function svgFileToString(iconpath){ fetch(iconpath) .then(response => response.text()) .then(text => { console.log(text); // do whatever }); } //svgFileToString('/icon.svg'); // for testing here on ST: svgFileToString('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCI+CiAgPHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iZ3JlZW4iIC8+Cjwvc3ZnPgo=');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.