index.html
<!DOCTYPE html>
<html>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Layer - Layer swipe effect</title>
  <style type="text/css">
    html,body{margin:0px;height:100%;width:100%}
    #map{width:100%;height:800px}
    #swipe{background-color:transparent;width:100%;border:none;height:10px;cursor:col-resize;margin-bottom:20px}
  </style>
  <link rel="stylesheet" href="https://unpkg.com/maptalks/dist/maptalks.css">
  <script type="text/javascript" src="https://unpkg.com/maptalks/dist/maptalks.min.js"></script>
  <body>
    <input type="range" id="swipe"/>
    <div id="map"></div>

    <script>
      var layer = new maptalks.TileLayer('light', {
        urlTemplate: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
        subdomains: ["a","b","c","d"],
        attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>',
        // force layer to render when map is zooming and moving
        'forceRenderOnMoving' : true,
        'forceRenderOnZooming' : true
      });

      var map = new maptalks.Map('map', {
        center: [121.4,37.5],
        zoom: 13,
        baseLayer : new maptalks.TileLayer('base',{
          'urlTemplate': 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
          'subdomains'  : ['a','b','c','d']
        }),
        layers : [layer]
      });

      var swipe = document.getElementById('swipe');

      var renderer = layer.getRenderer();
      var canvasGetter = renderer.getCanvasImage;

      var swipeCanvas = document.createElement('canvas');

      //override renderer's default method to get layer canvas image
      renderer.getCanvasImage = function () {
        var dpr = map.getDevicePixelRatio();
        //original layer canvas image
        var layerImage = canvasGetter.call(renderer);
        if (!layerImage || !layerImage.image) {
          return layerImage;
        }
        //drawn width after layer is erased by swipper
        var ctx = renderer.context;

        var width = renderer.canvas.width * (swipe.value / 100);
        var height = ctx.canvas.height;

        var leftCtx = swipeCanvas.getContext('2d');
        swipeCanvas.width = ctx.canvas.width;
        swipeCanvas.height = ctx.canvas.height;
        leftCtx.clearRect(0, 0, swipeCanvas.width, swipeCanvas.height);
        leftCtx.drawImage(layerImage.image, 0, 0, width, height, 0, 0, width, height);
        layerImage.image = swipeCanvas;
        return layerImage;
      };

      swipe.addEventListener('input', function () {
        //let layer redraw self in the next frame
        layer.getRenderer().setToRedraw();
      });

    </script>
  </body>
</html>
Copied!