gpt4 book ai didi

javascript - 获取动画线的计算值

转载 作者:行者123 更新时间:2023-11-29 10:52:14 25 4
gpt4 key购买 nike

这是我的代码:

<svg  id="canvas" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<line id="line" x1="100" y1="100" x2="150" y2="150" style="stroke:rgb(255,0,0);">
<animateTransform
attributeName="transform"
begin="0s"
dur="15s"
type="rotate"
from="0 100 100"
to="360 100 100"
repeatCount="indefinite"
/>
</line>
<script>
setInterval(function(){
var line = document.getElementById('line')
// This line returns "100 100"
console.log('point_1: ',line.x1.animVal.value, line.y1.animVal.value)
// This line returns "150 150"
console.log('point_2: ',line.x2.animVal.value, line.y2.animVal.value)
}, 500)
</script>
</svg>

我试图在动画过程中获取线坐标的计算值。但看起来 animVal.value 不起作用。

有什么办法可以得到这些值吗?

最佳答案

您不是在为点 x1x2 设置动画,而是在为 transform 设置动画。如果要在另一个坐标系中查看这些点的值,则需要将它们从线的坐标系转换到另一个空间。例如:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<style type="text/css">
circle { opacity:0.5 } #c1 { fill:green } #c2 { fill:blue }
</style>
<line id="line" x1="100" y1="100" x2="150" y2="150" stroke="red">
<animateTransform
attributeName="transform"
begin="0s" dur="15s"
type="rotate" repeatCount="indefinite"
from="0 100 100" to="360 100 100" />
</line>
<circle id="c1" r="5" /><circle id="c2" r="5" />
<text y="30">Hello</text>
<script type="text/javascript">
var svg = document.documentElement;
var line = document.getElementById('line')
var pt1 = svg.createSVGPoint(), pt2 = svg.createSVGPoint();
pt1.x = line.x1.baseVal.value; pt1.y = line.y1.baseVal.value;
pt2.x = line.x2.baseVal.value; pt2.y = line.y2.baseVal.value;
var c1 = document.getElementById('c1');
var c2 = document.getElementById('c2');
var t = document.getElementsByTagName('text')[0].childNodes[0];
setInterval(function(){
var lineToSVG = line.getTransformToElement(svg);
var p1 = pt1.matrixTransform( lineToSVG );
var p2 = pt2.matrixTransform( lineToSVG );
c1.cx.baseVal.value = p1.x; c1.cy.baseVal.value = p1.y;
c2.cx.baseVal.value = p2.x; c2.cy.baseVal.value = p2.y;
var angle = Math.round(Math.atan2(p2.y-p1.y,p2.x-p1.x)*180/Math.PI);
t.nodeValue = "Angle:" + angle +"°";
}, 200);
</script>
</svg>

在此处查看实际效果:http://phrogz.net/SVG/animated_point_values.svg

关于javascript - 获取动画线的计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com