【发布时间】:2018-01-01 21:58:01
【问题描述】:
我正在实现一个简单的游戏,玩家将控制屏幕中间的一个红色圆圈。圆圈被实现为 SVG 元素。
我希望能够使用 SVG 动画 (SMIL) 在 SVG 视图框中的任意两个位置之间移动圆。每个动画的触发是在屏幕上的任意位置单击鼠标左键。
我有 written code,我相信它应该可以在 Firefox 和 Chrome 中使用。在 Chrome 中,它仅适用于第一个动画,而对于所有后续动画,圆圈只是“传送”。在 Firefox 中没有动画 (控制台中没有错误)。
我的代码中是否存在错误,或者 SMIL 过于不成熟是否存在一些众所周知的问题?
我可以让 SMIL 在这个用例中工作还是应该改用画布?
这是我目前得到的代码:
<!DOCTYPE html>
<html>
<body>
<svg id="canvas" width="800" height="800" onclick="Move()">
<circle id="player1" cx="300" cy="300" r="40" stroke="blue" stroke-width="4" fill="red">
</circle>
</svg>
<script>
function createAnimation(attribute, playerID, duration, from, to) {
var animation = document.createElementNS("http://www.w3.org/2000/svg", "animate")
animation.setAttribute("attributeType", "XML")
animation.setAttribute("attributeName", attribute)
animation.setAttribute("dur", duration)
animation.setAttribute("to", to)
animation.setAttribute("from", from)
animation.setAttribute("fill", "freeze")
animationID = playerID + "animation" + attribute
animation.setAttribute("id", animationID)
player = document.getElementById(playerID)
previous_animation = document.getElementById(animationID)
if (previous_animation != null) {
player.removeChild(previous_animation)
}
player.appendChild(animation)
}
function Move() {
console.log(event.clientX);
console.log(event.clientY);
createAnimation("cx", "player1", "2s", document.getElementById("player1").getAttribute("cx"), event.clientX);
createAnimation("cy", "player1", "2s", document.getElementById("player1").getAttribute("cy"), event.clientY);
}
</script>
</body>
</html>
【问题讨论】:
标签: javascript animation svg smil