I managed to save on my hard drive a screenshot of a map generated with the Google Maps API using html2canvas. I now try to do the same thing with the MapBox API, and all I get on my hard drive is a black screen jpg.
Here is my HTML code :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/main.css">
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.12.2/mapbox-gl.js'></script>
<script src="js/html2canvas.js"></script>
</head>
<body onload="initialize()">
<div id="map"></div>
<script src="js/coordinates.js"></script>
</body>
</html>
Using this CSS to display it fullscreen :
html { height: 100%; }
body { height: 100%; margin: 0px; padding: 0px; }
#map_canvas { width: 100%; height: 100%; }
And this JS script to create the map and take the screenshot :
mapboxgl.accessToken = 'pk.eyJ1IjoiZ2luZ2FsYWJ2IiwiYSI6ImNpaWluNXIzbDAwMjB3ZG02c2hmNGhhMnUifQ.5SC9qnrK7eEdAtwv5Z0S_Q';
var latitude = 48.858565;
var longitude = 2.347198;
function initialize()
{
var map = new mapboxgl.Map(
{
container: 'map',
style: 'mapbox://styles/mapbox/dark-v8',
center: [2.347198, 48.858565],
zoom: 16,
pitch: 35
});
setTimeout(screenshot, 1000);
}
function screenshot()
{
html2canvas(document.body,
{
useCORS: true,
onrendered: function(canvas)
{
var image = document.createElement('a');
image.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
image.download = 'map.jpg';
image.click();
}
});
}
I use a one second timeout to be sure that the map is well created before taking the screenshot. To be sure it was the case, I even created a button in my DOM calling the screenshot() function when clicked, so I am sure that rendering time is not a problem.
I have read here : Print Mapbox/Leaflet Map that html2canvas could not correctly print the map because of some kind of fixed layouts. I wonder why it used to work with Google Maps maps, but never mind. Do you have any idea about that ?