Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 257
Shrinivas Pai Avatar asked Sep 02 '15 14:09

Shrinivas Pai


2 Answers

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/

like image 136
ischenkodv Avatar answered Oct 13 '22 13:10

ischenkodv


You can use XMLSerializer to serialize the SVG you want to send to canvg.

Something like this perhaps...

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>
like image 38
Robert Longson Avatar answered Oct 13 '22 14:10

Robert Longson