我有一个 SVG 和点(例如 (x,y) = (250,112))。 BATIK是否可以获取给定点的节点(DOM元素)?
我在由用户templth开发的batik用户论坛上找到了答案,我没有任何功劳,我只是在这里重新发布解决方案,这样它可以有更多的曝光。
public Element elementAtPosition(Document doc, Point2D point) {
UserAgent userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext context = new BridgeContext(userAgent, loader);
context.setDynamicState(BridgeContext.DYNAMIC);
GVTBuilder builder = new GVTBuilder();
GraphicsNode rootGraphicsNode = builder.build(context, doc);
// rootGraphicsNode can be offseted relative to coordinate system
// that means calling this method on coordinates taken directly from the svg file might not work
// check the bounds of rootGraphicsNode to determine where the elements actually are
// System.out.println(rootGraphicsNode.getBounds());
GraphicsNode graphicsNode = rootGraphicsNode.nodeHitAt(point);
if (graphicsNode != null) {
return context.getElement(graphicsNode);
} else {
// if graphicsNode is null there is no element at this position
return null;
}
}
在 Batik 1.9 上测试。此方法仅返回指定位置的最顶层元素。作为解决方法,您可以删除该元素并再次调用 nodeHitAt。
私有静态类 SVGMouseListener 实现 MouseListener {
private final JSVGCanvas svgCanvas;
public SVGMouseListener(JSVGCanvas jsvgCanvas) {
this.svgCanvas = jsvgCanvas;
}
@Override
public void mouseClicked(MouseEvent e) {
// Get the BridgeContext
BridgeContext bridgeContext = svgCanvas.getUpdateManager().getBridgeContext();
// Get the GraphicsNode at the SVG coordinates
GraphicsNode gvtRoot = svgCanvas.getGraphicsNode();
GraphicsNode svgNode = gvtRoot.nodeHitAt(new Point2D.Float(e.getX(), e.getY()));
// Handle the element
if (svgNode != null) {
Element element = bridgeContext.getElement(svgNode);
if (element != null) {
System.out.println("Clicked on element with ID: " + element.getAttribute("id"));
}
}
}
您需要致电: svgCanvas.setDocumentState(JSVGComponent.ALWAYS_DYNAMIC); 否则 svgCanvas 的 UpdateManager 为 null。