天地图Label文字居中

在使用自定义Label的时候,我们有文字居中显示的需求,但是天地图4.0截止2025年3月26日,官方并没有提供api方式;

效果图

核心方法
typescript 复制代码
// 借用canvas获取文字宽度高度
function getTextSize(text: string, font: string) {
	// 创建一个 canvas 元素
	const canvas = document.createElement('canvas');
	// 获取其 2D 绘图上下文
	const context: any = canvas.getContext('2d');
	// 设定字体样式
	context.font = `${font}`;
	// 测量文本宽度和高度
	const metrics = context.measureText(text);
	// 文本宽度和高度
	const width = metrics.width;
	const height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
	// 释放对 canvas 的引用,让垃圾回收机制可以回收它
	canvas.remove(); 
	return {textWidth: width, textHeight: height};
}
调用
typescript 复制代码
const {textWidth, textHeight} = methods.getTextSize('北京市小店区', 'normal 12px Arial');
const label= new T.Label({
	text: "北京市小店区",
	position: label.getLngLat(),
	/* textWidth/2: 宽度的一半
	   +10 是因为天地图默认样式是padding: 0 10;
	   -(textWidth / 2 + 10): 意思是向左偏移
	*/
	offset: new T.Point(-(textWidth / 2 + 10), -4)
});
// 自定义样式
label.setBackgroundColor('rgba(191, 224, 255, .11)');
label.setBorderColor('rgba(255, 255, 255, .2)');
label.setFontColor('#fff');
label.setFontSize(12);
// 追加到地图
map.addOverLay(label);
相关推荐
ywf12159 小时前
前端的dist包放到后端springboot项目下一起打包
前端·spring boot·后端
恋猫de小郭9 小时前
2026,Android Compose 终于支持 Hot Reload 了,但是收费
android·前端·flutter
hpoenixf15 小时前
2026 年前端面试问什么
前端·面试
还是大剑师兰特16 小时前
Vue3 中的 defineExpose 完全指南
前端·javascript·vue.js
泯泷16 小时前
阶段一:从 0 看懂 JSVMP 架构,先在脑子里搭出一台最小 JSVM
前端·javascript·架构
mengchanmian17 小时前
前端node常用配置
前端
华洛17 小时前
利好打工人,openclaw不是企业提效工具,而是个人助理
前端·javascript·产品经理
xkxnq17 小时前
第六阶段:Vue生态高级整合与优化(第93天)Element Plus进阶:自定义主题(变量覆盖)+ 全局配置与组件按需加载优化
前端·javascript·vue.js
A黄俊辉A18 小时前
vue css中 :global的使用
前端·javascript·vue.js
小码哥_常18 小时前
被EdgeToEdge适配折磨疯了,谁懂!
前端