天地图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);
相关推荐
Nexmoe几秒前
前端新手常踩的坑:方法一改全站崩
前端
Spider_Man1 分钟前
面试官的 JS 继承陷阱,你能全身而退吗?🕳️
前端·javascript·面试
happyCoder2 分钟前
实现AI聊天-核心技术点详解
前端
pepedd8643 分钟前
探究js继承实现方式-js面向对象的基础
前端·面试·trae
cos8 分钟前
FE Bits Vol.3|CSS attr() 类型化进化,PostCSS 复盘 12 年
前端·css·aigc
AliciaIr29 分钟前
深入理解HTTP:从协议基础到版本演进(上)
前端·http
pepedd86432 分钟前
数组字符串方法有哪些-带你重温js基础
前端·javascript·trae
pepedd86433 分钟前
深入理解js作用域-你真的懂js吗
前端·javascript·trae
阿迪州35 分钟前
[函数式编程] 为什么要柯里化?
前端
Cache技术分享43 分钟前
162. Java Lambda 表达式 - Consumer 的链式组合
前端·后端