Introduction to SVG's getTotalLength(), getPointAtLength() methods

getTotalLength

SVG path object.getTotalLength()
This method returns the user agent's calculated value of the total length of the path (in user units)

var a = SVGPathElement.getTotalLength()

getPointAtLength

SVG path object.getPointAtLength(len)
This method returns the coordinates of the point at the specified distance on the path
len
0~SVGPathElement.getTotalLength() floating point number, beyond the range will be converted into the maximum or minimum

var p = SVGPathElement.getPointAtLength(len)
// p.x, p.y 指定距离的点的坐标

Demo

demo based on d3.js

<!DOCTYPE html>
<html>

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<title>SVG 的 getTotalLength(), getPointAtLength() 方法简介</title>
	</head>

	<body>
		<svg width="200" height="200">
			<!--<path id="circle" d="M100 0  A 100 100 0 1 1 0 100" stroke="#f00" fill="green" stroke-width="1" />-->
		</svg>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			const container = d3.select('svg')

			container.append('circle')
				.attr('cx', '100')
				.attr('cy', '100')
				.attr('r', '100')
				.attr('fill', 'none')
				.attr('stroke', '#f00')
				.attr('id', 'circle')

			var Circle = container.select('#circle')
			var CircleLen = Circle.node().getTotalLength()

			for(var i = 0; i < 12; i++) {
     
     
				var p = Circle.node().getPointAtLength(i * CircleLen / 12)
				container.append("line")
					.attr("x1", "100")
					.attr("y1", "100")
					.attr("x2", p.x)
					.attr("y2", p.y)
					.attr("style", "stroke:rgb(0,0,0);stroke-width:1")
			}
		</script>
	</body>

</html>

//end

Guess you like

Origin blog.csdn.net/u013970232/article/details/114267994