随记~~~~~~
openlayers实现外阴影主要代码
/** 创建矢量图层 */
const addGradientStyle = (jsonUrl, zIndex) => {
const layerObj = new VectorLayer({
zIndex: zIndex || 1,
source: new VectorSource({
features: jsonFormat.readFeatures(jsonUrl) // TODO 此处为加载本地资源,可根据项目情况更改为自己的图层
}),
style: new Style({
renderer(coordinate, state) {
const [[x, y], [x1, y1]] = coordinate[0][0];
let arr = coordinate[0][0];
const ctx = state.context;
/** TODO 此处根据项目情况,设置阴影偏移个数 */
addOutlineShadow(ctx, {
fillStyle: "rgba(30, 60, 95,1)",
shadowOffsetY: 30,
shadowOffsetX: 2,
shadowColor: "rgba(30, 60, 95,1)",
coodArr: arr,
});
addOutlineShadow(ctx, {
fillStyle: "transparent",
shadowOffsetY: 20,
shadowOffsetX: 2,
shadowColor: "rgba( 56, 113, 139,1)",
coodArr: arr,
});
addOutlineShadow(ctx, {
fillStyle: "transparent",
shadowOffsetY: 15,
shadowOffsetX: 2,
shadowColor: "rgba(255,255,255,1)",
shadowBlur: 10,
coodArr: arr,
});
addOutlineShadow(ctx, {
fillStyle: "transparent",
shadowOffsetY: 10,
shadowOffsetX: 2,
shadowColor: "rgba(83, 173, 214,1)",
coodArr: arr,
});
addOutlineShadow(ctx, {
fillStyle: "transparent",
shadowOffsetY: 8,
shadowOffsetX: 2,
shadowColor: "rgba(255,255,255,1)",
shadowBlur: 10,
coodArr: arr,
});
addOutlineShadow(ctx, {
fillStyle: "rgba(30, 60, 95,1)",
shadowOffsetY: 5,
shadowOffsetX: 2,
shadowColor: "rgba(70, 133, 171,1)",
shadowBlur: 10,
coodArr: arr,
});
},
}),
});
map.value.addLayer(layerObj);
return layerObj;
}
/** 通过canvas绘制偏移图形 */
const addOutlineShadow = (ctx, option) => {
// 设置属性控制图形的外观
ctx.fillStyle = option.fillStyle || "transparent";
// 设置Y轴偏移量
ctx.shadowOffsetY = option.shadowOffsetY || 20;
// 设置X轴偏移量
ctx.shadowOffsetX = option.shadowOffsetX || 2;
// 设置模糊度
ctx.shadowBlur = option.shadowBlur || 2;
// 设置阴影颜色
ctx.shadowColor = option.shadowColor || "#000";
ctx.beginPath();
let arr = option.coodArr || [];
for (let i = 0; i < arr.length; i++) {
const data = arr[i];
if (i === 0) {
ctx.moveTo(data[0], data[1]);
} else {
ctx.lineTo(data[0], data[1]);
}
}
ctx.closePath();
ctx.fill();
ctx.stroke();
}