SVGTextContentElement: getCharNumAtPosition() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

SVGTextContentElement 接口的 getCharNumAtPosition() 方法用于表示在给定坐标系位置渲染文本字形时,导致该字形被渲染的字符。由于字符与字形之间不是一对一的关系,因此仅返回相关排版字符的第一个字符。

如果在指定位置找不到字符,则返回 -1

语法

js
getCharNumAtPosition(point)

参数

point

一个 DOMPoint 对象;坐标 (x, y) 表示要在用户坐标空间中检查字符位置。

返回值

一个长整数;与该位置对应的字符的索引。

示例

查找特定位置的字符

html
<svg width="200" height="100">
  <text id="exampleText" x="10" y="40" font-size="16">Hello, SVG World!</text>
</svg>
js
const textElement = document.getElementById("exampleText");

// Create a DOMPoint for the position (30, 40)
const point = new DOMPoint(30, 40);

// Get the character at the specified position
const charIndex = textElement.getCharNumAtPosition(point);

console.log(charIndex); // Output: 2 (for character "l")

// Check with a point where no character is present
const offPoint = new DOMPoint(300, 40);
const offCharIndex = textElement.getCharNumAtPosition(offPoint);

console.log(offCharIndex); // Output: -1 (no character found)

规范

规范
Scalable Vector Graphics (SVG) 2
# __svg__SVGTextContentElement__getCharNumAtPosition

浏览器兼容性