html2canvas SVG background image example
how to use html2canvas with SVG
Solution
HTML
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<div id="svgContainer">
<h1>Testing html2canvas with SVG</h1>
<img src="http://pngimg.com/uploads/simpsons/simpsons_PNG88.png" alt="" style="width:200px;height:auto;position:absolute;top:50px;right:0;display:none">
<div id='rootSvg'>
</div>
</div>
<button onclick="takeScreenShot()">to image</button>
CSS
button {
display: block;
height: 20px;
margin-top: 10px;
margin-bottom: 10px;
}
#svgContainer{
position: relative;
}
JavaScript
dataURItoBlob = function(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
};
downloadURI = function(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = URL.createObjectURL(dataURItoBlob(uri));
document.body.appendChild(link);
link.click();
link.remove();
}
window.takeScreenShot = function() {
html2canvas(document.body, {
logging: true,
allowTaint: false,
}).then(function(canvas) {
var myImage = canvas.toDataURL("image/png");
downloadURI("data:" + myImage, "yourImage.png");
});
};
loadImage = function() {
var svgTemplate = ' <svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="841.89px" height="595.28px" viewBox="0 0 841.89 595.28" enable-background="new 0 0 841.89 595.28" xml:space="preserve"> <defs> <clipPath id="a"> <rect x="562.761" y="32.243" width="145.388" height="145.389" ></rect> </clipPath> <clipPath id="b"> <rect x="238.52" y="418.523" width="218.669" height="145.391" ></rect> </clipPath> <clipPath id="c"> <rect x="537.429" y="383.635" width="174.813" height="180.279" ></rect> </clipPath> <clipPath id="d"> <rect x="129.735" y="32.518" width="181.466" height="364.668" ></rect> </clipPath> <clipPath id="e"> <rect x="342.655" y="97.852" width="281.6" height="401.865" ></rect> </clipPath> <clipPath id="f"> <rect x="196.5" y="172.799" width="364.955" height="145.119" ></rect> </clipPath> <clipPath id="g"> <rect x="163.116" y="449.162" width="145.389" height="72.111" ></rect> </clipPath> </defs> <g> <g id="svgPoly1" clip-path="url(#a)" class="droppable"> <image width="1200" height="1200" xlink:href=""></image> </g> <rect x="562.761" y="32.243" fill="none" stroke="#010202" stroke-miterlimit="10" width="145.388"...