2

In Mapbox GL JS I might do something like:

    const canvas = document.createElement("canvas");
    canvas.width = WIDTH;
    canvas.height = HEIGHT;

    map.addSource('canvas-source', {
       type: 'canvas',
       canvas: canvas,
       coordinates: [
           [WEST, NORTH],
           [EAST, NORTH],
           [EAST, SOUTH],
           [WEST, SOUTH]
       ]
    });
    
    map.addLayer({
        id: 'canvas-layer',
        type: 'raster',
        source: 'canvas-source'
    });

This will put a canvas on the map. I've read through the source of numerous plugins and they all seem to rely on a pattern of adding the canvas to the overlayPane map.getPane("overlayPane").appendChild(canvas), or using TileLayer \ GridLayer which both seem to create a new HTML element (createTile) for every point in the raster (which causes performance issues for large datasets). Lastly most of these plugins are old/unmaintained are there newer features of leaflet that would make this problem trivial?

1
  • There's already L.Canvas. Commented Apr 27 at 11:36

1 Answer 1

3

Yes, there is is simple way to put canvas image on map in Leaflet. After you create canvas, you create data URL using .toDataURL canvas method and display it on map using L.imageOverlay layer.

Here is sample code:

var map = L.map('map').setView([48.875, 2.35], 14);
    
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);


function renderCircle(ctx, point, radius) {
  ctx.fillStyle = 'rgba(60, 60, 255, 0.5)';
  ctx.strokeStyle = 'rgba(60, 60, 255, 0.9)';
  ctx.beginPath();
  ctx.arc(point.x, point.y, radius, 0, Math.PI * 2.0, true, true);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
};

const canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 300;
let ctx = canvas.getContext("2d");

renderCircle(ctx, {x: 150, y: 150}, 75);
const dataURL = canvas.toDataURL();

const bounds = [[48.868997582438254, 2.3318459217904604], [48.894552766073076, 2.355702853182322]];
L.imageOverlay(dataURL, bounds).addTo(map);

Result looks like this:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.