截至目前,Firefox 似乎不支持在
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns="http://www.w3.org/2000/svg"
width="400"
height="400"
version="1.1">
<g
id="layer1">
<circle cx="200" cy="200" r="180" style="fill:#ccf"/>
<path
style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none"
d="M 200,200 200,30">
<animateTransform
attributeName="transform"
attributeType="XML"
type="rotate"
from="0 200,200"
to="360 200,200"
dur="60s"
begin="1970-01-01T00:00:00Z"
repeatCount="indefinite"
/>
</path>
</g>
</svg>
如果我们将 begin= 更改为 0,则它会产生动画,但它与挂钟时间不同步。为了与挂钟时间同步,我认为我们必须计算相对于文档开始时间的开始值。
随着时间的推移,当我通过 AJAX 获取数据时,我将向文档添加动画元素,因此计算 begin 属性的代码必须在文档生命周期中的任何时间都有效。如果我们将此脚本标记添加到动画中,应该会使问题的本质更加清晰:
<script type="text/javascript">
function computeAnimationBegin()
{
// This is a toy function to illustrate the problem
var d1= new Date()
//console.log(d1.getTime())
d1.setSeconds(0)
d1.setMilliseconds(0)
return d1.getTime()
}
function wallclockToDocumentTime(t1)
{
// what magic goes here??
}
function adjustAnimation()
{
var elt = document.getElementById("a")
var t1 = computeAnimationBegin()
var val = wallclockToDocumentTime(t1)
console.log(val)
elt.setAttribute("begin", val)
}
window.onload = function() {
setInterval(adjustAnimation, 5*1000)
}
</script>
在 JavaScript 中,如何将挂钟时间映射到适合在 begin 属性中使用的值?
最佳答案
我最终所做的是使用“偏移值”。 Mozilla Description of Offset-Value
基本上,它允许您指定动画在相对于页面加载时间的特定秒数开始。
我具体做的是当“零”时(即在 window.onload 或任何 javascript 中)存储变量。
然后,对于我想要添加页面的每个动画,我将跟踪第二个变量,即我希望动画开始的挂钟时间。然后,我将 svg 的开头设置为:
var begin = (animation_start_time - page_load_time)/1000;
因此,就我而言,我有由第三方生成的 SVG(在我的情况下调用网络服务器),并且提前不知道何时需要将内容显示在屏幕上并移动。因此,我跟踪 page_load_time,每次我了解必须制作的新 SVG 时,我都会记录animation_start_time,并能够从中导出偏移值。
一开始这真的让我很困惑,因为我假设“偏移值”的动画创建时间为“零”(因此大多数东西的值都为零)。对我来说,页面加载时间为零似乎非常奇怪(您大多甚至不知道其值(value))。
为您提供代码问题的答案:
function wallclockToDocumentTime(t1)
{
return (t1 - page_load_time)/1000 + "s"; //s added so it fits directly into svg
}
哦,如果你担心 window.onload 发生在某些事情之后(它可能发生在奇怪的情况下),你可以通过输入以下内容来设置 page_load_time:
<script type="text/javascript">
// put this at the top so no other javascript can delay it
page_load_time = Date.now();
</script>
在任何其他 javascript(甚至是引用或库)之前。
关于javascript - 如何获取 HTML/SVG 文档的开始动画时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31973676/