javascript - 无法在 svg 中获得鼠标指针的精确 xy 坐标(在路径标签上)
问题描述
我正在开发一个基于科尔多瓦的网络应用程序。我有一些 svg 模板。当用户点击屏幕时,我想在用户点之间绘制路径。当用户单击svg 内的路径标记时,我无法获得准确的 xy 坐标。但是,当用户点击主 svg 空间时,它工作正常。请给我任何想法或解决方案。请检查下面的代码-
这是一个 svg 模板代码-
<div style="height:82vh">
<p style="text-align:center;margin:0px;padding-top:10px"> Ground Floor</p>
<svg id="final" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82vw" height="78vh"
viewBox="0 0 950 430" onclick="testsetNavigationPath(evt)">
<defs>
<filter id="dropshadow">
<feOffset result="offOut" in="SourceGraphic" dx="10" dy="10" />
<feColorMatrix result="matrixOut" in="offOut" type="matrix" values="0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0" />
<feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="50" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<g id="gFinal" transform="matrix(0.72,0,0,-0.72,13,720)" >
<g transform="scale(0.1,0.1)" id="g12">
<path id="parking01".../>
.
.
.
.
</g>
</g>
</svg>
这是js代码-
function testsetNavigationPath(evt) {
debugger
var e = document.getElementById('body');
var scope = angular.element(e).scope();
var svg = document.getElementById('final');
NS = svg.getAttribute('xmlns');
var
t = evt.target,
x = evt.clientX,
y = evt.clientY,
target = (t == svg ? svg : t.parentNode),
svgP = svgPoint(target, x, y),
circle = document.createElementNS(NS, 'circle');
console.log("click coordinates"+ Math.round(svgP.x) + ","+ Math.round(svgP.y));
circle.setAttributeNS(null, 'cx', Math.round(svgP.x));
circle.setAttributeNS(null, 'cy', Math.round(svgP.y));
circle.setAttributeNS(null, 'r', 10);
target.appendChild(circle);
scope.check = parseInt(scope.check) + 1;
if(parseInt(scope.check)<= 1){
pathAttr = 'M ' + Math.round(svgP.x) + ' ' + Math.round(svgP.y);
scope.dPath = scope.dPath + pathAttr;
}
else{
pathAttr = ' L ' + Math.round(svgP.x) + ' ' + Math.round(svgP.y);
scope.dPath = scope.dPath + pathAttr;
}
if(parseInt(scope.check) > 3){
testnavigateFromHome(scope.dPath);// this function draw the path based on points.
}
}
//**getting svg coordinates**
function svgPoint(element, x, y) {
var svg = document.getElementById('final')
var pt = svg.createSVGPoint();
pt.x = x;
pt.y = y;
return pt.matrixTransform(element.getScreenCTM().inverse());
}
此图像显示当用户单击主 svg 空间时它工作正常。 但用户点击 svg path ,它会画出侧屏。这意味着 xy 坐标在路径标记上不准确。所以它指向一些地方。这第二张图片 -
解决方案
推荐阅读
- azure-functions - 如何解决 Alexa 问题请求的技能响应?
- c++ - 在声明的同一行从 lambda 返回值
- reactjs - React ref.current 内部循环仅在第一次迭代时起作用
- python - 如何根据列唯一集将行保留在 DataFrame 中?
- typescript - 如何在 Typescript 中指定数字的最小-最大范围?
- css - 我无法以角度设置身体背景图像
- python - Tkinter 透明框架文本未显示
- javascript - 如何根据内容中的过滤器编号隐藏表格?
- c++ - ONNX 模型中的转发过程失败
- python - 哪些内置抽象基类支持切片?