9

我正在使用canvg()函数转换svgcanvas. 如果我们canvg()直接在 onload 上使用,它将全部转换svgcanvas. 我想转换svg与特定div的 .

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与之相关divid=apply.

小提琴演示在这里

4

2 回答 2

9

我在canvg本身的源代码中找到了您问题的答案:canvg

您需要更改查询选择器以从您的 div 中选择 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);
}

这是您修改的示例:http: //jsfiddle.net/ischenkodv/L3hondLn/135/

于 2015-09-14T20:15:26.370 回答
3

您可以使用 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>

于 2015-09-02T15:01:10.920 回答