如何为特定 div 应用 canvg() 函数?
How to apply canvg() function for particular div?
我正在使用 canvg()
函数将 svg
转换为 canvas
。
如果我们直接在 onload 上使用 canvg()
,它会将所有 svg
转换为 canvas
。
我想转换与特定 div
.
相关的 svg
Html
<div id="notapply">
<svg><text x="50" y="50">Not to Apply!</text></svg>
</div>
<div id="apply">
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
</div>
脚本
canvg();
在这里它应该转换 svg
与 div
相关,后者有 id=apply
.
您可以使用 XMLSerializer 序列化要发送到 canvg 的 SVG。
也许是这样的……
canvg("canvas", (new XMLSerializer).serializeToString(document.getElementById("apply").firstElementChild));
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvg/1.5/canvg.min.js"></script>
<div id="notapply">
<svg><text x="50" y="50">Not to Apply!</text></svg>
</div>
<div id="apply">
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
</div>
<canvas id="canvas" width="500" height="500"></canvas>
我在canvg本身的源代码中找到了关于你问题的答案:canvg
您需要从您的 div 中更改查询 select 或 select SVG:
// Your selector here
var svgTags = document.querySelectorAll('#apply svg');
// Process SVG tags
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var c = document.createElement('canvas');
c.width = svgTag.clientWidth;
c.height = svgTag.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
我正在使用 canvg()
函数将 svg
转换为 canvas
。
如果我们直接在 onload 上使用 canvg()
,它会将所有 svg
转换为 canvas
。
我想转换与特定 div
.
svg
Html
<div id="notapply">
<svg><text x="50" y="50">Not to Apply!</text></svg>
</div>
<div id="apply">
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
</div>
脚本
canvg();
在这里它应该转换 svg
与 div
相关,后者有 id=apply
.
您可以使用 XMLSerializer 序列化要发送到 canvg 的 SVG。
也许是这样的……
canvg("canvas", (new XMLSerializer).serializeToString(document.getElementById("apply").firstElementChild));
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvg/1.5/canvg.min.js"></script>
<div id="notapply">
<svg><text x="50" y="50">Not to Apply!</text></svg>
</div>
<div id="apply">
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
</div>
<canvas id="canvas" width="500" height="500"></canvas>
我在canvg本身的源代码中找到了关于你问题的答案:canvg
您需要从您的 div 中更改查询 select 或 select SVG:
// Your selector here
var svgTags = document.querySelectorAll('#apply svg');
// Process SVG tags
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var c = document.createElement('canvas');
c.width = svgTag.clientWidth;
c.height = svgTag.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}