jieter/leaflet-headless

Provide easy access to the canvas before and after leaflet draws on it

nyurik opened this issue · 2 comments

For our usecase, it would be great to add an image (from a buffer) to the canvas before leaflet gets to draw on it. What would be the best way to do this? Thx!

I think I got a workaround - https://github.com/kartotherian/kartotherian-server/blob/leaflet/lib/imager.js#L28 - it is still broken (if the center is shifted, the box and the tiles go in the oposite direction), but its a proof of concept. I still suspect there is a memory leak though.

Little late to the party, but it could be handy for next generations :-)

If you need to, for example, save JPEG to the buffer instead of saving PNG to file.

const L = require('leaflet-headless');

L.Map.prototype.toJpegBuffer = function (callback) {
    var leafletImage = require('leaflet-image');

    leafletImage(this, function (err, canvas) {
        if (err) {
            console.error(err);
            return;
        }
        canvas.toDataURL('image/jpeg', 0.9, (err, jpeg) => {
            if (err) {
                console.error(err);
                return;
            }
            const data = jpeg.replace(/^data:image\/\w+;base64,/, '');
            callback(Buffer.alloc(data.length, data, 'base64'));
        })
    });
};

// ... create 'map' and all other initial settings

map.toJpegBuffer(buffer => {
    // do whatever you need with the buffer
})