Biloutage Biloutage - 1 year ago 143
Javascript Question

Screenshoting MapBox using html2canvas creates a black jpg

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>
<link rel="stylesheet" href="css/main.css">
<script src=''></script>
<script src="js/html2canvas.js"></script>

<body onload="initialize()">
<div id="map"></div>
<script src="js/coordinates.js"></script>

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()
useCORS: true,
onrendered: function(canvas)
var image = document.createElement('a');
image.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream"); = 'map.jpg';;

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 ?

Answer Source

Mapbox has a built in screenshot api:

or Grab the canvas data to image via for mapboxgl, you'll need to set preserveDrawingBuffer option for this to work which is off by default... see

 var img = new Image();
 var mapCanvas = document.querySelector('.mapboxgl-canvas');
 img.src = mapCanvas.toDataURL();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download