Reputation: 31
I am converting the whole page into canvas, now I want to convert it into an image that I can download:
html2canvas(document.body, {
allowTaint: true,
onrendered: function(canvas) {
document.body.appendChild(canvas).setAttribute("id", "canvas");
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
img.setAttribute('crossOrigin', 'anonymous');
document.write('<img src="'+img+'"/>');
}
});
That works but I get this error in console and the image isn't created
Uncaught (in promise) DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Upvotes: 2
Views: 3192
Reputation: 1789
If you can post the image data to a php script, it is very simple.
Posting data to php:
var imgData = canvas.toDataURL('image/png');
$.post("https://path-to-your-script/capture.php", {image: imgData},
function(data) {
console.log('posted');
});
Collecting data in php script:
capture.php
$data = $_POST['image'];
// remove "data:image/png;base64," from image data.
$data = str_replace("data:image/png;base64,", "", $data);
// save to file
file_put_contents("/tmp/image.png", base64_decode($data));
Upvotes: -1
Reputation: 1067
Try this:
<a id="download"
onclick="var download = document.getElementById('download');
download.href = document.getElementById('canvasElementId').toDataURL();
download.download='imageName.png'">
Save Canvas Image</a>
You had all that excess stuff you didn't need and it would generate an image that you have to do an extra step by right clicking and saving. This is way easier and works better.
If it has an error saying that "tainted canvases can't be exported", then you could remove the taint if it doesn't work and if you can be able to with your application.
Upvotes: 0