且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 svg 元素坐标转换为屏幕坐标?

更新时间:2023-02-11 11:14:15

当我想要做同样的事情时(了解哪些屏幕坐标对应于 SVG 坐标),我正在玩弄下面的这个片段.我认为简而言之,这就是您所需要的:

I was playing around with this snippet below when I wanted to do the same (learn which screen coordinates correspond to the SVG coordinates). I think in short this is what you need:

  1. 学习SVG元素的当前变换矩阵(你感兴趣的坐标),大致:matrix = element.getCTM();

  1. Learn current transformation matrix of the SVG element (which coordinates you are interested in), roughly: matrix = element.getCTM();

然后通过执行获取屏幕位置,大致:position = point.matrixTransform(matrix),其中point"是一个SVGPoint.

Then get screen position by doing, roughly: position = point.matrixTransform(matrix), where "point" is a SVGPoint.

请参阅下面的代码段.我通过更改浏览器窗口大小来玩这个,并正在改变 svg 坐标以匹配 div 元素的坐标

See the snippet below. I was playing with this by changing browser window size and was altering svg coordinates to match those of the div element

// main SVG:
var rootSVG = document.getElementById("rootSVG");
// SVG element (group with rectangle inside):
var rect = document.getElementById("rect");
// SVGPoint that we create to use transformation methods:
var point = rootSVG.createSVGPoint();
// declare vars we will use below:
var matrix, position;
// this method is called by rootSVG after load:
function init() {
  // first we learn current transform matrix (CTM) of the element' whose screen (not SVG) coordinates we want to learn:
  matrix = rect.getCTM();
  // then we "load" SVG coordinates in question into SVGPoint here:
  point.x = 100;  // replace this with the x co-ordinate of the path segment
  point.y = 300;  // replace this with the y co-ordinate of the path segment
  // now position var will contain screen coordinates:
  position = point.matrixTransform(matrix);
  console.log(position)
  // to validate that the coordinates are correct - take these x,y screen coordinates and apply to CSS #htmlRect to change left, top pixel position. You will see that the HTML div element will get placed into the top left corner of the current svg element position.
}

html, body {
	margin: 0;
	padding: 0;
	border: 0;
	overflow:hidden;
	background-color: #fff;	
}
svg {
      position: fixed; 
	  top:0%; 
	  left:0%; 
	  width:100%; 
	  height:100%; 
	  background:#fff;	  
}
#htmlRect {
  width: 10px;
  height: 10px;
  background: green;
  position: fixed;
  left: 44px;
  top: 132px;
}

<body>
  <svg id="rootSVG" width="100%" height="100%" viewbox="0 0 480 800" preserveAspectRatio="xMinYMin meet" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="init()">

    <g id="rect">
      <rect id="rectangle" x="100" y="300" width="400" height="150"/>
    </g>

  </svg>
  <div id="htmlRect"></div>
</body>