设置矢量Polygon 样式颜色为渐变色
第一步:网上查找设置渐变色
var pixelRatio = DEVICE_PIXEL_RATIO;
var vectorLayer = new VectorLayer({
source: new VectorSource({
url: 'data/geojson/countries.geojson',
format: new GeoJSON()
}),
style: getStackedStyle
});
var fill = new Fill();
var getStackedStyle = function(feature) {
var id = feature.getId();
fill.setColor(gradient);
return style;
};
var vectorLayer = new VectorLayer({
source: new VectorSource({
url: 'data/geojson/countries.geojson',
format: new GeoJSON()
}),
style: getStackedStyle
});
var gradient = (function() {
var grad = context.createLinearGradient(0, 0, 512 * pixelRatio, 0);
grad.addColorStop(0, 'red');
grad.addColorStop(1 / 6, 'orange');
grad.addColorStop(2 / 6, 'yellow');
grad.addColorStop(3 / 6, 'green');
grad.addColorStop(4 / 6, 'aqua');
grad.addColorStop(5 / 6, 'blue');
grad.addColorStop(1, 'purple');
return grad;
})();
这样无法控制到每条线的颜色,完全超出自己的控制,我这是水管,我想要每个水管上有渐变色,但是显然这种方法不行
第二步:控制到每一个元素的样式,然后设置渐变色
const newStyle = new Style({
renderer(coordinates, state) {
const pointsX = coordinates[0].map((obj) => obj[0]);
const pointsY = coordinates[0].map((obj) => obj[1]);
const startPoint = [Math.min(...pointsX), Math.min(...pointsY)];
const endPoint = [Math.max(...pointsX), Math.max(...pointsY)];
const ctx = state.context;
const grad = ctx.createLinearGradient(startPoint[0], startPoint[1], startPoint[0], endPoint[1]);
grad.addColorStop(0, '#00FFFF');
grad.addColorStop(0.3, '#66FFFF');
grad.addColorStop(0.5, '#CCFFFF');
grad.addColorStop(0.7, '#66FFFF');
grad.addColorStop(1, '#00FFFF');
ctx.beginPath();
ctx.fillStyle = grad;
ctx.moveTo(coordinates[0][0][0], coordinates[0][0][1]);
for (let i = 0; i < coordinates[0].length; i++) {
ctx.lineTo(coordinates[0][i][0], coordinates[0][i][1]);
}
ctx.fill();
},
});
return newStyle;
如果你的颜色需要更多颜色则在addColorStop里面多加几个,完美解决!!!