1
<svg width="100%" height="100%"
    xmlns="http://www.w3.org/2000/svg" version="1.1" 
    xmlns:xlink="http://www.w3.org/1999/xlink"
    onload="startup(evt)">
<script>
function startup(evt){
    svgDoc=evt.target.ownerDocument;
    setInterval(function(){step("zero");},1000);
    setInterval(function(){follow("zero","one");},950);
}

function step(e,follower){
    e=svgDoc.getElementById(e);
    var rand = Math.floor((Math.random()*2)+1);
    var rand2 = Math.floor((Math.random()*2)+1);
    var move = 10;
    var y = +(e.getAttribute("y"));
    var x = +(e.getAttribute("x"));
    if(rand == 1){  
        if(rand2 == 1){
        e.setAttribute("y",y + move);
        } else {
        e.setAttribute("y",y - move);
        }
    } else {
    if(rand2 == 1){
        e.setAttribute("x",x + move);
        } else {
        e.setAttribute("x",x - move);
        }
    }
}
function follow(leader, follower){
    follower = svgDoc.getElementById(follower);
    leader = svgDoc.getElementById(leader);

    var leaderY = leader.getAttribute("y");
    var leaderX = leader.getAttribute("x");

    follower.setAttribute("y", leaderY);
    follower.setAttribute("x", leaderX);
}

</script>   
<defs>
    <text id="zero">0</text>
    <text id="one">1</text>
</defs>
<use x="50" y="50" xlink:href="#zero"/>
<use x="10" y="10" xlink:href="#one"/>
</svg>

只是做一些随机练习来构建我的逻辑和练习脚本。

基本上,我的意思是“一”跟随“零”。零随机移动,它的位置在假设移动之前被放入内存/存储一点点(50ms)。然后将其设置为该位置。相反,我只是按照“零”的运动模式得到“一”,而不是它之前的位置。我很好奇为什么会这样,因为我没有对“one”svg 元素做任何实际的添加。

4

1 回答 1

4

这里有几个问题。

首先 0 和 1 没有以开头的属性,因此 getAttribute 将返回 null。将您的标记更改为此将修复它

<defs>
    <text id="zero" x="0" y="0">0</text>
    <text id="one" x="0" y="0">1</text>
</defs>

其次 getAttribute 返回一个字符串,因此您需要使用 parseFloat 从中获取一个数字,例如

var y = parseFloat(e.getAttribute("y"));
var x = parseFloat(e.getAttribute("x"));

进行这两个更改似乎使它做你想做的事

于 2012-10-08T16:10:10.503 回答