Reputation: 1101
I have 3 dynamic div here and am trying to convert the dynamic div to image format for privew section,how to convert the dynamic divs to image format? any idea?
and also need to hide the dynamic divs and shows only the images, please provide a fiddle
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
Upvotes: 1
Views: 1259
Reputation: 6531
I made a quick implementation with the help of jQuery and a quick look at one of the canvas examples at MDN. Definitely not the best way to do but you'll get the idea.
One more thing is you might want to watch out for security issues when Drawing DOM content to Canvas.
jQuery('#htmlBlock').html(jQuery('#editor').val());
jQuery('#editor').on('change', function() {
jQuery('#htmlBlock').html(jQuery(this).val());
});
jQuery('#html2img').on('click', function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
template[3] = jQuery('#htmlBlock').html();
var svg = new Blob([template.join('')], {
type: 'image/svg+xml;charset=utf-8'
});
var url = DOMURL.createObjectURL(svg);
jQuery('#imgitem').attr('src', url);
});
var DOMURL = window.URL || window.webkitURL || window;
var template = [
'<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">',
'<foreignObject width="100%" height="100%">',
'<div style="background-color: #AAA;max-width: 140px; padding: 10px;" xmlns="http://www.w3.org/1999/xhtml">',
'',
'</div>',
'</foreignObject>',
'</svg>'
];
#htmlBlock {
background-color: #AAA;
max-width: 140px;
padding: 10px;
}
label {
display: block;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="editor" placeholder="editor">HelloWorld</textarea>
<button id="html2img">HTML2IMAGE</button>
<label>
HTML:
<div id="htmlBlock">
</div>
</label>
<label>
Image:
<div>
<img id="imgitem" />
</div>
</label>
Upvotes: 0
Reputation: 5356
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
// Clean up
//document.body.removeChild(canvas);
}
});
});
});
Check this for reference.
Upvotes: 1