【发布时间】:2019-10-31 13:58:00
【问题描述】:
这个问题可能比 svg 本身更与数学有关。
在主 svg 中,通过 viewBox 属性获得了多个转换后的 svg(来自不同的事件)。
在这些 svg 中,其他元素分组在 g 中,使用 matrix transformations 进行修改。
如何获取鼠标指针变换后的元素上的点。
目标可以是绘制一个点或获取相关点,作为图表。
let point = document.getElementById("main").createSVGPoint();
// The mouse cursor points
point.x = 180
point.y = 63
mouse = point.matrixTransform(sub.getCTM())
// console.log(mouse)
// Output
// "x": 611.75439453125,
// "y": 68.71578979492188
// Testing:
circle.setAttribute("cx", 611.75439453125)
circle.setAttribute("cy", 68.71578979492188)
// Not working
<!-- Parent svg -->
<!-- Not preserving aspect ratios -->
<svg id="main" viewBox="0 0 300 400">
<!-- Includes others svg, transformed with a viewBox -->
<!-- Not preserving aspect ratios -->
<svg id="group1" viewBox="7 54 10 570">
<!-- Group element modified with a matrix -->
<!-- Using css to define the matrix behave identicaly -->
<!-- All elements in this group are transformed by this matrix -->
<g id="sub" transform="matrix(4.5,0,0,0.84,-140,99)">
<!-- Exemple element in group -->
<polyline points="4 65.94338623003772 5 78 6 50.10565885410098 7 40.95007190251531 8 53.698867220021675 9 49.43265131064406 10 44.36112722960851 11 56.329540580770356 12 49.785452985846554 13 44.10803037565898 14 40.537830814642945 15 41.84933269419995 16 38.33857254585345 17 43.590332265307744 18 49.16421525342487 19 49.49017332290519 20 42.51658803643061 21 46.943865580139814 22 36.27544970608283 23 38.070136488634255 24 43.46186643792423 25 42.20788657062835 26 48.37424628503659 27 25.58210762671243 28 23.927391073996347 29 22.349370537628886 30 30.592274894669004 31 21.97356005752208 32 24.960869894290738 33 23.221787723591348 34 17.41781668642936 35 2 36 19.335217095138404 37 39.60405681560149 38 38.49579937936788 39 32.47132729520408 40 25.016474506143126 41 27.037414536922626 42 27.541690844412955 43 20.37253071624997 44 9.872846078159213 45 17.79362716653617 46 13.107500567651172 47 24.955117693064494 48 24.247596942250766 49 19.728284178923616 50 11.341574791230315 51 8.248807931982782 52 10.697328253903962 " ></polyline>
<!-- This circle should be at the cursor -->
<circle id="circle" cx="50" cy="50" r="50"fill="blue">
</g>
</svg>
<!-- Rectangles symbolizing the mouse cursor -->
<rect width="1000" height="1" x="0" y="63" ></rect>
<rect width="1" height="500" x="180" y="0"></rect>
</svg>
Svg 有很多与变换相关的绑定,我们可以用 getCTM() 和getBBox() 检索每个元素的变换矩阵,并使用matrixTransform。
这适用于一级转换?
如何链接多个矩阵变换?
【问题讨论】:
-
不清楚...你想要相对于变换空间的位置(即你的
应该在 中)还是相对于未变换空间的位置(就像现在一样)? -
是的,当然,圆圈在 g 中,在最后一级变换中。已编辑谢谢。
-
你希望它只来自指针事件还是能够转换任意点?
-
实际上,仅从屏幕/视图框中当前可见的坐标,所以是的,从指针到容器 svg
group1中的点,与鼠标显示的内容相匹配。例如,我代表一个时间序列,可以在计划中缩放和转换。
标签: javascript svg matrix css-transforms cartesian-coordinates