Search code examples
javascriptjquerycanvassvgcanvg

How to apply canvg() function for particular div?


I am using canvg() function to convert svg into canvas. If we use canvg() directly on onload it will convert all svg to canvas. I wanted to convert svg related to particular 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>

Script

canvg();

Here it should convert svg related to div which is having id=apply.

Fiddle demo here


Solution

  • I have found an answer on your question in the source code of canvg itself: canvg

    You need to change query selector to select SVG from your div:

    // 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);
    }
    

    Here is your example modified: http://jsfiddle.net/ischenkodv/L3hondLn/135/