tsayen / dom-to-image

Generates an image from a DOM node using HTML5 canvas
Other
10.21k stars 1.68k forks source link

Not capturing markers on leaflet map #402

Closed lewisMachilika closed 2 years ago

lewisMachilika commented 2 years ago

i have the below code that is able to capture the map to a png file using dom-to-image however the markers on the map are not captured. I wanted to capture them as well how can I achieve that?

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel="stylesheet" href="static/leaflet.css"   crossorigin=""/>

    <script src="static/leaflet.js"    crossorigin=""></script>
    <script src="static/dom-to-image.min.js"></script>
    <style>
        #map,#my_location { height: 500px; }
    </style>
</head>
<body>
    <div id="map"></div>
    <script src="static/html2canvas.js"></script>
    <script src="static/jquery-3.5.1.min.js"></script>
    <script>
        var mymap = L.map('map').setView([51.505, -0.09], 13);
        L.tileLayer(
            "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
            {"detectRetina": false, "maxNativeZoom": 18, "maxZoom": 18, "minZoom": 0, "noWrap": false, "opacity": 1, "subdomains": "abc", "tms": false}
        ).addTo(mymap);

        var popup = L.popup();

        function onMapClick(e) {
            popup
                .setLatLng(e.latlng)
                .setContent("You clicked the map at " + e.latlng.toString())
                .openOn(mymap);
                const screenshotTarget = document.body;
                domtoimage.toBlob(document.getElementById('map'))
                     .then(function (blob) {
                         var image = new Image();
                         image.src = URL.createObjectURL(blob);
                         $("#map").html("<img src=\"\" id=\"my_location\"/>");
                         $("#my_location").attr({'src':image.src});

                     });

        }
        mymap.on('click', onMapClick);
    </script>    
</body>
</html>

map-screenshot

lewisMachilika commented 2 years ago

i just needed to call the below code outside onMapClick function it worked fine

                domtoimage.toBlob(document.getElementById('map'))
                     .then(function (blob) {
                         var image = new Image();
                         image.src = URL.createObjectURL(blob);
                         $("#map").html("<img src=\"\" id=\"my_location\"/>");
                         $("#my_location").attr({'src':image.src});

                     });