本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。
源码 见 1031.html ,对应的 官网示例 https://openlayers.org/en/latest/examples/icon.html?q=style
image.png使用Interaction处理点选图标的交互
使用on监听鼠标事件动态修改鼠标指针样式
通过hasFeatureAtPixel判断鼠标位置是否为图标
效果时单击后,图标由绿色变成粉红色
image.png
<!DOCTYPE html>
<html>
<head>
<title></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 view = new ol.View({
center: [0, 0],
zoom: 3
});
//为点状要素添加样式
function createStyle(src, img) {
return new ol.style.Style({
image: new ol.style.Icon(
{
anchor: [0.5, 0.96],
crossOrigin: "anonymous",
// color:[255,0,0],
src: src,
img: img,//img和src同时存在时,img覆盖src
imgSize: img ? [img.width, img.height] : undefined
}
)
});
}
// 点要素
var iconFeature = new ol.Feature(new ol.geom.Point([0, 0]));
// 设置样式
iconFeature.set(
"style",
createStyle(
"../data/icon.png",
undefined
)
);
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.Stamen({ layer: "watercolor" })
}),
new ol.layer.Vector({
style: function (feature) {
return feature.get("style");
},
source: new ol.source.Vector({ features: [iconFeature] })
})
],
target: "map",
view: view
});
//用来标记已经选择到的样式
var selectStyle = {};
//当选中时,设置样式
var select = new ol.interaction.Select({
style: function (feature) {
var image = feature
.get("style")
.getImage()
.getImage();//最后这个getImage,可能返回img也可能返回src
// 如果选择样式中不存在该样式,则创建样式
if (!selectStyle[image.src]) {
// 创建canvas元素
var canvas = document.createElement("canvas");
// 获取绘图环境
var context = canvas.getContext("2d");
// 画布宽高
canvas.width = image.width;
canvas.height = image.height;
// 绘制图像
context.drawImage(image, 0, 0, image.width, image.height);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
// 图片像素反向,创建负片
for (var i = 0, ii = data.length; i < ii; i = i + (i % 4 == 2 ? 2 : 1)) {
data[i] = 255 - data[i];
}
context.putImageData(imageData, 0, 0);
// 创建样式并添加到选择样式中
selectStyle[image.src] = createStyle(undefined, canvas);
}
return selectStyle[image.src];
}
});
map.addInteraction(select);
// 鼠标移到要素上时改变鼠标样式,由箭头变成小手
map.on("pointermove", function (evt) {
map.getTargetElement().style.cursor = map.hasFeatureAtPixel(evt.pixel)
? "pointer"
: "";
});
</script>
</body>
</html>
网友评论