OpenLayers 自定义圆形渲染(renderer)

158 阅读3分钟

前言

OpenLayers中,使用Style样式类进行图形渲染,除了填充属性fill、描边属性stroke等之外,还可以使用renderer属性自定义渲染样式,当使用renderer进行渲染时,fillstrokeimage等属性将会被忽略。

1. renderer属性

renderer作为Style对象的一个属性,是RenderFunction类型,也就是一个渲染函数。这个方法具有两个参数

  • coordinatesGeoJSON格式的Geometry对象像素值坐标。
  • State:图层渲染器状态对象。

2. renderer渲染

通过Feature对象setStyle方法添加要素样式,从而使用renderer渲染器自定义渲染方式。从state参数中获取到canvas上下文对象,再调用canvas方法createRadialGradient创建径向渐变模式,然后使用addColorStop方法添加渐变色,形成渐变条带,最后就是调用arc方法绘制圆形,fill属性填充样式,stroke方法进行描边。

circleFeature.setStyle(new ol.style.Style({
    renderer(coordinates, state) {
        // 解构坐标对
        const [[x, y], [x1, y1]] = coordinates
        // 获取canvas上下文对象
        const ctx = state.context

        // 计算x和y方向距离
        const dx = x1 - x
        const dy = y1 - y

        const radius = Math.sqrt(dx * dx + dy * dy)
        const innerRadius = 0
        const outerRadius = radius * 1.4

        // 创建径向渐变
        const gradient = ctx.createRadialGradient(
            x,
            y,
            //  innerRadius,
            10,
            x,
            y,
            outerRadius
        )
        // 添加渐变色带
        gradient.addColorStop(0'#ff00cc')
        gradient.addColorStop(0.35'#ffcc00')
        gradient.addColorStop(0.7'#00ffcc')
        gradient.addColorStop(1'#ff0066')

        // 开始绘制
        ctx.beginPath()
        // 创建圆形
        ctx.arc(x, y, radius, 02 * Math.PItrue)
        ctx.fillStyle = gradient
        ctx.fill()

        ctx.arc(x, y, radius, 02 * Math.PItrue)
        ctx.strokeStyle = '#ffcc00'
        ctx.stroke()
    }
}))

3. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>自定义圆形渲染</title>
    <meta charset="utf-8" />

    <link rel="stylesheet" href="../../../libs/css/ol9.2.4.css">

    <script src="../../../js/config.js"></script>
    <script src="../../../libs/js/ol9.2.4.js"></script>

    <style>
        * {
            padding0;
            margin0;
            font-size14px;
            font-family'微软雅黑';
        }

        html,
        body {
            width100%;
            height100%;
        }

        #map {
            position: absolute;
            top50px;
            bottom0;
            width100%;
        }

        #top-content {
            position: absolute;
            width100%;
            height50px;
            line-height50px;
            backgroundlinear-gradient(135deg#ff00cc#ffcc00#00ffcc#ff0066);
            color#fff;
            text-align: center;
            font-size32px;
        }

        #top-content span {
            font-size32px;
        }

        #layer-container {
            position: absolute;
            top15%;
            left20px;
            width20%;
            bottom5%;
            background#fff;
            color#fff;
            border1px solid #ddd;
            border-radius2.5px;
        }

        .layer-head {
            background#16baaa;
            padding10px;
            margin-bottom15px;
        }
    </style>
</head>

<body>
    <div id="top-content">
        <span>自定义圆形渲染</span>
    </div>
    <div id="map" title="地图显示"></div>

</body>

</html>

<script>
    //地图投影坐标系
    const projection = ol.proj.get('EPSG:3857');
    //==============================================================================//
    //============================天地图服务参数简单介绍==============================//
    //================================vec:矢量图层==================================//
    //================================img:影像图层==================================//
    //================================cva:注记图层==================================//
    //======================其中:_c表示经纬度投影,_w表示球面墨卡托投影================//
    //==============================================================================//
    const TDTImgLayer = new ol.layer.Tile({
        title"天地图影像图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图影像",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const TDTCvaLayer = new ol.layer.Tile({
        title"天地图注记图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图注记",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const TDTVecLayer = new ol.layer.Tile({
        title"天地图矢量图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图矢量",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })

    const map = new ol.Map({
        target"map",
        loadTilesWhileInteractingtrue,
        viewnew ol.View({
            center: [104.063598616048730.660919181071225],
            zoom5,
            worldsWrapfalse,
            minZoom1,
            maxZoom20,
            projection"EPSG:4326"
        }),
        layers: [TDTImgLayerTDTCvaLayerTDTVecLayer],
        // 地图默认控件
        controls: ol.control.defaults.defaults({
            zoomfalse,
            attributiontrue,
            rotatefalse
        })
    })

    // 监听地图单击事件
    map.on('click'evt => {
        console.log("获取地图坐标:", evt.coordinate)
    })

    const circleFeature = new ol.Feature({
        geometrynew ol.geom.Circle([
            104.62609807960689,
            33.71857664673769
        ], 5)
    })

    circleFeature.setStyle(new ol.style.Style({
        renderer(coordinates, state) {
            // 解构坐标对
            const [[x, y], [x1, y1]] = coordinates
            // 获取canvas上下文对象
            const ctx = state.context

            // 计算x和y方向距离
            const dx = x1 - x
            const dy = y1 - y

            const radius = Math.sqrt(dx * dx + dy * dy)
            const innerRadius = 0
            const outerRadius = radius * 1.4

            // 创建径向渐变
            const gradient = ctx.createRadialGradient(
                x,
                y,
                //  innerRadius,
                10,
                x,
                y,
                outerRadius
            )
            // 添加渐变色带
            gradient.addColorStop(0'#ff00cc')
            gradient.addColorStop(0.35'#ffcc00')
            gradient.addColorStop(0.7'#00ffcc')
            gradient.addColorStop(1'#ff0066')

            // 开始绘制
            ctx.beginPath()
            // 创建圆形
            ctx.arc(x, y, radius, 02 * Math.PItrue)
            ctx.fillStyle = gradient
            ctx.fill()

            ctx.arc(x, y, radius, 02 * Math.PItrue)
            ctx.strokeStyle = '#ffcc00'
            ctx.stroke()
        }
    }))
    const circleLayer = new ol.layer.Vector({
        sourcenew ol.source.Vector({
            features: [circleFeature]
        })
    })
    map.addLayer(circleLayer)
</script>

OpenLayers示例数据下载,请回复关键字:ol数据

全国信息化工程师-GIS 应用水平考试资料,请回复关键字:GIS考试

【GIS之路】 已经接入了智能助手,欢迎关注,欢迎提问。

欢迎访问我的博客网站-长谈GIShttp://shanhaitalk.com

都看到这了,不要忘记点赞、收藏 + 关注

本号不定时更新有关 GIS开发 相关内容,欢迎关注 !