Javascript Animation - SVG 形状消失



我刚刚进入JS,所以我可能错过了一些东西。我正在尝试使用鼠标悬停对 SVG 矩形进行动画处理,以便形状看起来正在"逃离"鼠标。当我尝试通过添加来更改 x 和 y 时,形状消失了。如果我减去,它的行为符合预期。

任何帮助将不胜感激。

HTML
     <svg width="1200" height="600">
         <rect x="100" y="100" width="100" height="100" id="firstShape" onmouseover="moveShape(firstShape);">               
     </svg>
Javascript
     function moveShape(obj) {
                var newX = obj.getAttribute("x") + 5;
                var newY = obj.getAttribute("y") + 5;           
                obj.setAttribute("x", newX);
                obj.setAttribute("y", newY);
      }

属性是字符串,Javascript处理字符串和数字的方式非常草率。

您实际所做的是将"5"添加到"100"并得到"1005"。

如果在修改属性之前将属性转换为整数,则代码将正常工作。

function moveShape(obj) {
  var newX = parseInt(obj.getAttribute("x")) + 5;
  var newY = parseInt(obj.getAttribute("y")) + 5;
  obj.setAttribute("x", newX);
  obj.setAttribute("y", newY);
}
<svg width="1200" height="600">
  <rect x="100" y="100" width="100" height="100" id="firstShape" onmouseover="moveShape(firstShape);">               
</svg>

最新更新