Reputation: 2150
I need to download an image file with a single click on a link or button that is drawn dynamically with the given content on the end users. The image is drawn by the HTML5 canvas.
I've tried this
function download() {
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var img = document.getElementById('bg');
var imgLogo = document.getElementById('logo');
ctx.drawImage(img, 0, 0, 160, 600);
ctx.drawImage(imgLogo, 30, 100, 86, 86);
var imgData = ctx.getImageData(0, 0, c.width, c.height);
ctx.putImageData(imgData, 0, 0);
var data = c.toDataURL('images/jpeg');;
this.href = data;
}
The hidden button is:
<a id="downloadButton" class="btn btn-info" download="name.jpeg" style="display:none;">Hidden Button</a>
I need to download the image on another button click like the button bellow
<a id="anotherButton" class="btn btn-info">Download as image</a>
I've tried this code but it's not working
$('.download-img').on('click', function(e){
e.preventDefault();
download();
return false;
});
For a single button this code is working fine with this code
downloadButton.addEventListener('click', download, false);
But I need to click on "anotherButton" and make the same things happen. How is that possible?
Any help?
Upvotes: 0
Views: 799
Reputation: 194
Check my JS Fiddle- JSFIDDLE
You will get an idea at least. You can use html2canvas
to achieve this. You need to add the following scripts -
Scripts library
jQuery Library & html2canvas.js
HTML
<span id="contentbox">
<div class="header">
<div class="title ng-binding">Samrat Khan</div>
</div>
</span>
<br/>
<input type="button" id="btnSave" value="Save PNG"/>
<div id="outputaspng"></div>
Scripts
$(function() {
$("#btnSave").click(function() {
html2canvas($("#contentbox"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
Canvas2Image.saveAsPNG(canvas);
$("#outputaspng").append(canvas);
// Clean up
//document.body.removeChild(canvas);
}
});
});
});
html2canvas plugin has some limitation, don't avoid to read that
Limitations All the images that the script uses need to reside under the same origin for it to be able to read them without the assistance of a proxy. Similarly, if you have other canvas elements on the page, which have been tainted with cross-origin content, they will become dirty and no longer readable by html2canvas.
The script doesn't render plugin content such as Flash or Java applets. It doesn't render iframe content either.
Upvotes: 1