Search code examples
javascriptcanvasleafletreact-leafletleaflet.draw

How to use L.canvas to draw a fluctuating circle


I am a back-end programmer who is using leaflet for the first time. I don’t know much about js animation steps. I want to use L.canvas to draw a dynamic circle, just like the picture below. enter image description here

enter image description here

Specify the range of the circle or the latitude and longitude of the center of the circle, and the radius will continue to fluctuate and spread outward, similar to water waves (this effect in the picture is made by me using a highly encapsulated animation library)

I hope someone can provide me with an example, or give me a suggestion so that I can smoothly draw a dynamic circle on the map. thanks a lot


Solution

  • You can create mutliple circles and update the radius each millisecond:

    var canvasRenderer = L.canvas();
    
    function createWavingCircle(latlng, color, fromRadius, toRadius){
        var circle = L.circle(latlng, {radius: fromRadius, color, renderer: canvasRenderer}).addTo(map);
        var nextCircle;
        var interval = setInterval(()=>{
            var radius = circle.getRadius()+1;
            if(radius <= toRadius){
                circle.setRadius(radius);
                if(Math.round((radius / toRadius) * 100) >= 30 && !nextCircle){
                    nextCircle = createWavingCircle(latlng, color, fromRadius, toRadius);
                }
            } else {
                if(nextCircle && nextCircle.getRadius() >= toRadius){
                    circle.remove();
                    clearInterval(interval);
                }
            }
        },1)
        return circle;
    }
    
    // replace this values with your custom ones
    createWavingCircle(map.getCenter(), 'red', 10, 400);
    

    https://plnkr.co/edit/IT5VcxokeCWpkpEx