【问题标题】:SVG getAttribute/setAttribute simply adding to coordinates instead of "setting"?SVG getAttribute/setAttribute 只是添加到坐标而不是“设置”?
【发布时间】:2012-10-09 00:10:10
【问题描述】:
<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 元素做任何实际的添加。

【问题讨论】:

  • 是否可以选择使用javascript?

标签: javascript svg


【解决方案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"));

做出这两个改变似乎让它做你想做的事

【讨论】:

  • 谢谢。我不知道属性会为空。我想在 SetIntervals 之前的某一时刻使用 set 属性也可以解决为空的问题。另外,我想我可以使用 var x = +(e.getAttribute("x"));将其解析为数字,就像我在 step() 函数中所做的那样。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多