隨記~~~~~~
openlayers實現(xiàn)外陰影主要代碼
/** 創(chuàng)建矢量圖層 */
const addGradientStyle = (jsonUrl, zIndex) => {
const layerObj = new VectorLayer({
zIndex: zIndex || 1,
source: new VectorSource({
features: jsonFormat.readFeatures(jsonUrl) // TODO 此處為加載本地資源,可根據(jù)項目情況更改為自己的圖層
}),
style: new Style({
renderer(coordinate, state) {
const [[x, y], [x1, y1]] = coordinate[0][0];
let arr = coordinate[0][0];
const ctx = state.context;
/** TODO 此處根據(jù)項目情況,設(shè)置陰影偏移個數(shù) */
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) => {
// 設(shè)置屬性控制圖形的外觀
ctx.fillStyle = option.fillStyle || "transparent";
// 設(shè)置Y軸偏移量
ctx.shadowOffsetY = option.shadowOffsetY || 20;
// 設(shè)置X軸偏移量
ctx.shadowOffsetX = option.shadowOffsetX || 2;
// 設(shè)置模糊度
ctx.shadowBlur = option.shadowBlur || 2;
// 設(shè)置陰影顏色
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();
}