官网demo地址:
这是一个在地图上绘制渐变圆形的示例。
首先创建一个圆形的feature
const circleFeature = new Feature({
geometry: new Circle([12127398.797692968, 4063894.123105166], 50),
});
由于openlayers的style属性中,没有提供一个特定的api设置渐变色,因此我们在这里利用style中的renderer函数获取图形的坐标点,拿到canvas,自定义canvas的样式后显示在地图上来实现渐变色效果。
参数coordinates是绘制图形的坐标数组,state是上下文。
const [[x, y], [x1, y1]] = coordinates;
const ctx = state.context;
const dx = x1 - x;
const dy = y1 - y;
通过圆心和圆周点的坐标计算圆的半径。
const radius = Math.sqrt(dx * dx + dy * dy);
定义内外半径,渐变的内半径为0,外半径为圆的1.4倍
const innerRadius = 0;
const outerRadius = radius * 1.4;
创建放射状渐变
const gradient = ctx.createRadialGradient(
x,
y,
innerRadius,
x,
y,
outerRadius
);
定义渐变的颜色停止点
gradient.addColorStop(0, "rgba(255,0,0,0)");
gradient.addColorStop(0.6, "rgba(255,0,0,0.2)");
gradient.addColorStop(1, "rgba(255,0,0,0.8)");
然后按照canvas绘制圆形的方式 绘制图层。
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI, true); //绘制一个圆形路径。
ctx.fillStyle = gradient; //设置填充样式为之前定义的渐变。
ctx.fill(); // 填充圆形区域
// 绘制圆的边界
ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
ctx.strokeStyle = "rgba(255,0,0,1)";
ctx.stroke();
完整代码:
<template>
<div class="box">
<h1>自定义圆形渲染、绘制渐变色圆形</h1>
<div id="map"></div>
</div>
</template>
<script>
import Feature from "ol/Feature.js";
import Map from "ol/Map.js";
import View from "ol/View.js";
import { Circle } from "ol/geom.js";
import { OSM, Vector as VectorSource } from "ol/source.js";
import { Style } from "ol/style.js";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer.js";
export default {
name: "",
components: {},
data() {
return {
map: null,
};
},
computed: {},
created() {},
mounted() {
const circleFeature = new Feature({
geometry: new Circle([12127398.797692968, 4063894.123105166], 50),
});
circleFeature.setStyle(
new Style({
renderer(coordinates, state) {
console.log('state',state);
// 解构坐标数组,获取圆心和圆周上的一个点的坐标
const [[x, y], [x1, y1]] = coordinates;
const ctx = state.context;
const dx = x1 - x;
const dy = y1 - y;
//通过圆心和圆周点的坐标计算圆的半径。
const radius = Math.sqrt(dx * dx + dy * dy);
// 定义内外半径
//渐变的内半径为0,外半径为圆的1.4倍
const innerRadius = 0;
const outerRadius = radius * 1.4;
// 创建放射状渐变
const gradient = ctx.createRadialGradient(
x,
y,
innerRadius,
x,
y,
outerRadius
);
// 定义渐变的颜色停止点
gradient.addColorStop(0, "rgba(255,0,0,0)");
gradient.addColorStop(0.6, "rgba(255,0,0,0.2)");
gradient.addColorStop(1, "rgba(255,0,0,0.8)");
// 绘制圆并填充渐变色
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI, true); //绘制一个圆形路径。
ctx.fillStyle = gradient; //设置填充样式为之前定义的渐变。
ctx.fill(); // 填充圆形区域
// 绘制圆的边界
ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
ctx.strokeStyle = "rgba(255,0,0,1)";
ctx.stroke();
},
})
);
new Map({
layers: [
new TileLayer({
source: new OSM(),
visible: true,
}),
new VectorLayer({
source: new VectorSource({
features: [circleFeature],
}),
}),
],
target: "map",
view: new View({
center: [12127398.797692968, 4063894.123105166],
zoom: 19,
}),
});
},
methods: {},
};
</script>
<style lang="scss" scoped>
#map {
width: 100%;
height: 500px;
}
.box {
height: 100%;
}
</style>