尽管通常情况下, 我们不应该将这种逻辑用于生产资料, 因为总有更好的选择来阻止你执行此操作, 有时这并不取决于你, 而是取决于第三方。无论你是从Web上剪贴内容, 还是创建修改某些矢量图像的自动化脚本, 了解如何将浏览器中渲染的SVG节点转换为base64格式的图片这一简单技巧都不会损害你。
考虑以下在浏览器的DOM中呈现的SVG元素的示例, 该元素具有一个使其成为dom一部分的id, 即mySvgElement:
<svg id="mySvgElement" xmlns="http://www.w3.org/2000/svg" height="179.2" width="179.2">
<g>
<path transform="scale(0.1, -0.1) translate(0, -1536)" d="M1536 224v704q0 40 -28 68t-68 28h-704q-40 0 -68 28t-28 68v64q0 40 -28 68t-68 28h-320q-40 0 -68 -28t-28 -68v-960q0 -40 28 -68t68 -28h1216q40 0 68 28t28 68zM1664 928v-704q0 -92 -66 -158t-158 -66h-1216q-92 0 -158 66t-66 158v960q0 92 66 158t158 66h320 q92 0 158 -66t66 -158v-32h672q92 0 158 -66t66 -158z" style=" fill: #03a9f4; "/>
</g>
</svg>
在浏览器中渲染后, 它将显示如下图片:
为了将该元素转换为其base64表示形式, 我们只需要DOM元素和XMLSerializer类的帮助即可。 XMLSerializer接口提供了serializeToString()方法, 以构造表示DOM树的XML字符串。在我们的案例中, 使用上述元素, 我们将要做:
// 1. Keep a DOM reference to the SVG element
var SVGDomElement = document.getElementById("mySvgElement");
// 2. Serialize element into plain SVG
var serializedSVG = new XMLSerializer().serializeToString(SVGDomElement);
// 3. convert svg to base64
var base64Data = window.btoa(serializedSVG);
// The generated string will be something like:
// PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdm.........
// If you want to display it in the browser via URL:
console.log("data:image/svg+xml;base64, " + result);
请注意, 由XMLSerializer生成的序列化字符串将返回纯SVG, 因此将其编码为base64, 我们将获得纯base64数据:
PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTc5LjIiIHdpZHRoPSIxNzkuMiI+Cgk8Zz4KCQk8cGF0aCB0cmFuc2Zvcm09InNjYWxlKDAuMSwtMC4xKSB0cmFuc2xhdGUoMCwtMTUzNikiIGQ9Ik0xNTM2IDIyNHY3MDRxMCA0MCAtMjggNjh0LTY4IDI4aC03MDRxLTQwIDAgLTY4IDI4dC0yOCA2OHY2NHEwIDQwIC0yOCA2OHQtNjggMjhoLTMyMHEtNDAgMCAtNjggLTI4dC0yOCAtNjh2LTk2MHEwIC00MCAyOCAtNjh0NjggLTI4aDEyMTZxNDAgMCA2OCAyOHQyOCA2OHpNMTY2NCA5Mjh2LTcwNHEwIC05MiAtNjYgLTE1OHQtMTU4IC02NmgtMTIxNnEtOTIgMCAtMTU4IDY2dC02NiAxNTh2OTYwcTAgOTIgNjYgMTU4dDE1OCA2NmgzMjAgcTkyIDAgMTU4IC02NnQ2NiAtMTU4di0zMmg2NzJxOTIgMCAxNTggLTY2dDY2IC0xNTh6IiBzdHlsZT0iJiMxMDsgICAgZmlsbDogIzAzYTlmNDsmIzEwOyIvPgoJPC9nPgo8L3N2Zz4=
如果要使用数据URL表示形式在浏览器中显示它, 则需要在生成的数据” data:image / svg + xml; base64″中添加前缀:
data:image/svg+xml;base64, PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTc5LjIiIHdpZHRoPSIxNzkuMiI+Cgk8Zz4KCQk8cGF0aCB0cmFuc2Zvcm09InNjYWxlKDAuMSwtMC4xKSB0cmFuc2xhdGUoMCwtMTUzNikiIGQ9Ik0xNTM2IDIyNHY3MDRxMCA0MCAtMjggNjh0LTY4IDI4aC03MDRxLTQwIDAgLTY4IDI4dC0yOCA2OHY2NHEwIDQwIC0yOCA2OHQtNjggMjhoLTMyMHEtNDAgMCAtNjggLTI4dC0yOCAtNjh2LTk2MHEwIC00MCAyOCAtNjh0NjggLTI4aDEyMTZxNDAgMCA2OCAyOHQyOCA2OHpNMTY2NCA5Mjh2LTcwNHEwIC05MiAtNjYgLTE1OHQtMTU4IC02NmgtMTIxNnEtOTIgMCAtMTU4IDY2dC02NiAxNTh2OTYwcTAgOTIgNjYgMTU4dDE1OCA2NmgzMjAgcTkyIDAgMTU4IC02NnQ2NiAtMTU4di0zMmg2NzJxOTIgMCAxNTggLTY2dDY2IC0xNTh6IiBzdHlsZT0iJiMxMDsgICAgZmlsbDogIzAzYTlmNDsmIzEwOyIvPgoJPC9nPgo8L3N2Zz4=
现在应该产生:
编码愉快!
评论前必须登录!
注册