本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。
源码 见 1043.html ,对应的 官网示例 https://openlayers.org/en/latest/examples/canvas-gradient-pattern.html?q=style
canvas的createLinearGradient和createPattern
使用不同的ol.style.Color样式化不同的要素
image.png
image.png
<!DOCTYPE html>
<html>
<head>
<title>使用canvas编程样式化要素</title>
<link rel="stylesheet" href="../include/ol.css" type="text/css" />
<script src="../include/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');//绘图上下文
var pixelRatio = ol.has.DEVICE_PIXEL_RATIO;//缓存当前硬件设备到绘图模型上的像素分辨率,屏幕像素和实际绘图像素的比例
//绘制渐变图案
var gradient = (function() {
var grad = context.createLinearGradient(0, 0, 1080 * 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;
})();
//绘制点状图案
var pattern = (function() {
canvas.width = 8 * pixelRatio;
canvas.height = 8 * pixelRatio;
context.fillStyle = 'white';
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'rgba(102, 0, 102, 0.5)';
context.beginPath();
context.arc(4 * pixelRatio, 4 * pixelRatio, 3 * pixelRatio, 0, 2 * Math.PI);
context.fill();
context.fillStyle = 'rgb(55, 0, 170)';
context.beginPath();
context.arc(4 * pixelRatio, 4 * pixelRatio, 1.5 * pixelRatio, 0, 2 * Math.PI);
context.fill();
return context.createPattern(canvas, 'repeat');
}());
var fill = new ol.style.Fill(); //声明填充样式,会根据需求动态修改填充样式
var style = new ol.style.Style({
fill: fill,
stroke: new ol.style.Stroke({ //描边的颜色
color: '#333',
width: 2
})
});
//通过feature的ID,改变填充样式的颜色
var getStackedStyle = function(feature) {
var id = feature.getId();
console.log(id)
fill.setColor(id > 'J' ? gradient : pattern);
return style;
};
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: '../data/lands.geojson',
format: new ol.format.GeoJSON()
}),
style: getStackedStyle
});
var map = new ol.Map({
layers: [
vectorLayer
],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([16, 48]),
zoom: 3
})
});
</script>
</body>
</html>
网友评论