天地图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);
相关推荐
刘发财2 小时前
弃用html2pdf.js,这个html转pdf方案能力是它的几十倍
前端·javascript·github
牛奶5 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶5 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
Kagol7 小时前
🎉OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用!
前端·开源·agent
GIS之路8 小时前
ArcGIS Pro 中的 notebook 初识
前端
JavaGuide9 小时前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
ssshooter9 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
格砸10 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
Live0000010 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉10 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化