Wechat: yu389741| Email: gisdqy@163.com

Shop:https://www.giserdqy.com/shop

OpenLayer4实现卷帘效果


一、用途:卷帘效果在多个图层叠加的时候会用到。但是还想两个图层相互切换或者两个图层在一块,这个时候就用到卷帘效果,我们可以把这个卷帘做成一个label可以来回拖动,这样既可以达到控制效果,也很美观。

先来张效果图:

二、全部源码

<!DOCTYPE html>
<html>
<head>
    <title>地图卷帘效果</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.4/css/ol.css" type="text/css">
    <script src="https://openlayers.org/en/v4.6.4/build/ol.js"></script>
    <style>
        body {
            overflow: hidden;
        }

        html, body, .map {
            width: 100%;
            height: 100%;
            position: absolute;
            box-sizing: border-box;
            padding: 0;
            margin: 0;
        }
        .swipe {
            position: absolute;
            top: 15px;
            left: 40px;
            z-index: 9;
            width: auto;
        }

            .swipe input[type=range] {
                width: 300px;
            }
    </style>
</head>
<body>

    <div class="swipe">
        卷帘:<input type="range" min="0" max="100" step="1" id="swipe" value="8"><br />       
    </div>
    <div id="map" class="map"></div>
    <script>
        function getTdtLayer(lyr) {
            var url = "http://t{0-7}.tianditu.com/DataServer?T=" + lyr + "&X={x}&Y={y}&L={z}";
            var layer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    url: url
                })
            });
            return layer;
        }
        var vec_c = getTdtLayer("vec_w");
        var cva_c = getTdtLayer("cva_w");
        var img_c = getTdtLayer("img_w");
        var veclayerGroup = new ol.layer.Group({
            layers: [vec_c, cva_c]
        });
        var imglayerGroup = new ol.layer.Group({
            layers: [img_c, cva_c]
        });
        var map = new ol.Map({
            target: "map",
            view: new ol.View({
                projection: "EPSG:4326",
                center: [115.7555794477557, 22.6070466884657],
                zoom: 7
            }),
            layers: [
                imglayerGroup, veclayerGroup               
            ]
        });
        var swipe = document.getElementById('swipe');
        vec_c.on('precompose', function (event) {
            var ctx = event.context;
            console.log(swipe.value);
            var width = ctx.canvas.width * (swipe.value / 100);

            ctx.save();
            ctx.beginPath();
            ctx.rect(width, 0, ctx.canvas.width - width, ctx.canvas.height);
            ctx.clip();
        });
        vec_c.on('postcompose', function (event) {
            var ctx = event.context;
            ctx.restore();
        });
        swipe.addEventListener('input', function () {
            map.render();
        }, false);
    </script>
</body>
</html>

三、总结

这个卷帘效果的实现主要是通过渲染事件获得context进行裁剪图,这个比网上流传那个两个div感觉更好点,其实我们在做效果还是什么都会用到canvas,应该好好地看看canvas的使用

转载自:https://blog.csdn.net/weixin_40184249/article/details/81515302