openlayers - OpenLayers 5 - 有没有办法使集群文本居中?
问题描述
我正在制作显示我的标记的应用程序,因为其中有很多我需要制作集群。除文本外的所有内容都按预期工作。
我尝试过更改锚点和锚点[X/Y]Units,但即使我将其更改为固定像素,它也总是呈现错误。
这是我的代码:
const style = new Style({
image: new CircleStyle({
radius: 12,
stroke: new Stroke({
color: '#ffffff',
width: 1,
}),
fill: new Fill({
color: '#3399CC'
}),
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
anchor: [0.5, 0.5],
}),
text: new Text({
font: '14px/24px sans-serif',
text: '2',
fill: new Fill({
color: '#ffffff'
})
})
});
var clusters = new VectorLayer({
source: clusterSource,
style: style
});
群集中的文本未正确对齐。我附上一些图片来进一步说明问题。
解决方案
我认为单独使用 OpenLayers API 无法正确对齐它。我想出了另一个解决方案。我做了一个函数来在 Canvas Context 中渲染圆圈和文本。
我使用这个功能:
const createImage = function (diameter, text) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// set canvas width and height to double the outer diameter
canvas.width = diameter * 2;
canvas.height = diameter * 2;
// white border
ctx.beginPath();
ctx.arc(diameter, diameter, diameter, 0, 2 * Math.PI);
ctx.fillStyle = '#ffffff';
ctx.fill();
// inner circle
ctx.beginPath();
ctx.arc(diameter, diameter, diameter - 1.5, 0, 2 * Math.PI); // the -1.5 makes a nice offset
ctx.fillStyle = '#104ddb';
ctx.fill();
// text in the circle
ctx.beginPath();
ctx.font = '14px Arial';
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'center'; // center horizontally
ctx.textBaseline = 'middle'; // center vertically
ctx.fillText(text, diameter, diameter);
return canvas.toDataURL();
};
样式如下所示:
style = new Style({
image: new Icon({
src: createImage(24, '2'), // createImage(radius, text)
imgSize: [24, 24],
}),
});
我希望它可以帮助某人。
推荐阅读
- r - 使用 dplyr 枚举 data.frame 中的冗余值
- php - 为什么 jquery ajax 阻止加载另一个 url 页面
- angular - 获取 URL 参数 ActivatedRoute Angular
- makefile - 在多个 Makefile 中包含 Makefile 和 Echo 变量
- android - Worker 内部的 Synchronous 或 Asynchronous Rxjava(来自 WorkManager 组件)什么是正确的选择?
- wordpress - 适用于 WordPress 的时尚注册表单插件
- python-3.x - python deepcopy不深度复制用户类?
- javascript - 同一页面上 angular 2 指令的多个实例
- docker - 使用 Chrome 进行 Docker Swarm 负载平衡测试
- java - 在实时数据流中查找前k个频繁词