I would like to take a screenshot of my page.
The initial code I found here:
https://retifrav.github.io/blog/2018/07/23/html-js-screenshot/
which in my case looks like this:
function makeScreenshot() {
html2canvas(document.getElementById("screenshot"), {scale: 2}).then(canvas => {
canvas.id = "map";
canvas.crossOrigin = "Anonymous";
var main = document.getElementById("main");
while (main.firstChild) {
main.removeChild(main.firstChild);
}
console.log(main);
main.appendChild(canvas);
});
}
document.getElementById("a-make").addEventListener('click', function()
{
document.getElementById("a-make").style.display = "none";
makeScreenshot();
document.getElementById("a-download").style.display = "inline";
}, false);
document.getElementById("a-download").addEventListener('click', function()
{
this.href = document.getElementById("map").toDataURL();
this.download = "canvas-image.png";
}, false);
and HTML:
<div id="map">
<div id="screenshot">
<div id="popup" class="ol-popup">
<a href="#" id="popup-closer" class="ol-popup-closer"></a>
<div id="popup-content"></div>
</div>
</div>
<a id="a-make" href="#">Make a screenshot</a>
<a id="a-download" href="#" style="display:none;">Download a screenshot</a>
</div>
The console says:
Uncaught (in promise) TypeError: Cannot read property 'firstChild' of null at index.html:146
and next
**Uncaught TypeError: document.getElementById(...).toDataURL is not a function
at HTMLAnchorElement.<anonymous> (index.html:164)**
which is more important I guess, because I can't export my screenshot.
I found some solution here:
and tried to implement into my code:
canvas.crossOrigin = "Anonymous";
just underneath the
canvas.id = "map";
and
var canvas = document.getElementById('map').querySelector('canvas');
var dataURL = canvas.toDataURL();
just above the
this.href = document.getElementById("map").innerHTML = dataURL();
this.download = "canvas-image.png";
}, false);
The fiddle is here
https://jsfiddle.net/kyzLfur3/
Does anyone know where the problem might be?
Your id="map"
element is a div
. They don't have toDataURL
. canvas
elements do, but not div
s.
Elsewhere in the question you show code looking for a canvas
within that div
:
var canvas = document.getElementById('map').querySelector('canvas');
var dataURL = canvas.toDataURL();
So if at some point a canvas
gets added to the #map
div
, you might want to add that to your click
handler:
document.getElementById("a-download").addEventListener('click', function()
{
this.href = document.getElementById("map").querySelector('canvas').toDataURL();
// ^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−
this.download = "canvas-image.png";
}, false);