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) 保存されます。次に、この位置に設定することを意図しています。代わりに、以前の位置ではなく、「ゼロ」の移動パターンに従って「ワン」を取得します。「1つの」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"));

これらの2つの変更を加えることで、あなたが望むことができるようです

于 2012-10-08T16:10:10.503 に答える