Oddomir
Oddomir

Reputation: 81

html2canvas "screenshot" of a div element containing Google drive directions map

I'm trying to make a "screenshot" of a div element where a Google map resides. I use html2canvas and do not face any problem when it comes to "regular maps" (displaying some location with with one or a few markers on a map). However, the problem arises with driving directions map - the map that connects two points with the calculated route. This map is probably not just a bunch of layers / images but also uses a google directionsService and directionsDisplay services that are responsible for calculating and drawing the route. (maybe this can't be done in the background when html2canvas try to reconstruct "the image”). Finally, I'm getting SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

There are a several questions on the StackOverflow, pretty close to this case, but none of them describes exactly the same scenario neither solution is provided.

I know security background of this problem and CORS principles. Analysing headers there could be found the line Access-Control-Allow-Origin: *. Also each other map is rendered without any problem, so I can't see here the root cause of this specific problem.

Also, as far as I know, this couldn’t be overridden using Google's static maps because route couldn't be drawn to the static map.

This is the code:

    html2canvas(document.getElementById('map'), {

//"proxy": "/html2canvasproxy.php",
 //proxy is not used
"logging": true,

"useCORS": true,

"onrendered": function (canvas) {

var img = new Image();

img.onload = function () {

img.onload = null;

img.setAttribute('crossOrigin', 'anonymous');
 document.getElementById("output").appendChild(img);
 };

img.src = canvas.toDataURL("image/png");
 //error line
}

});

Upvotes: 1

Views: 1801

Answers (1)

Oddomir
Oddomir

Reputation: 81

Some old syntax and ugly code, but this should be something that worked at the end...

screenShot ( i ) {
        html2canvas( document.getElementById( 'map' + i), {
            "logging": true,
            "useCORS": true
        } ).then( function ( canvas ) {
            var encodedString = canvas.toDataURL( "image/png" );

            // sending encoded base64 image to the server
            googleMaps.$http.post( '/api/screenshots', {
                appraisalId: googleMaps.$data.appraisal_id,
                encodedScreenshot: encodedString,
                tag: 'googlemaps',
                index: i,
            } ).then( function ( response ) {
                googleMaps.setButtonsCaptions();
                console.log( response.data.success );
            }, function ( response ) {
                console.log( response );
                console.log( 'Problem while sending screenshot to the server' )
            }.bind( googleMaps ) );
        } );
    }

Upvotes: 0

Related Questions