我想移动到一个矩形。当它到达行尾时,进行换行并将其放在下一行的开头。矩形不会很好地坐标以使换行。有任何想法吗?这是我的功能:
<script type="text/javascript"><![CDATA[
var rect = document.getElementById('player');
var x = rect.getAttribute('x')*1,
y = rect.getAttribute('y')*1;
setInterval(move, 30);
function move()
{
if (rect.getAttribute('x') < 500){
rect.x.baseVal.value = ++x;
}
else if (rect.getAttribute('x') >= 500){
rect.x.baseVal.value = x-250;
rect.y.baseVal.value = y+250;
}
}
]]></script>
谢谢!
答案 0 :(得分:1)
从元素中获取值是不必要的昂贵,在您的情况下,它似乎得到或设置值太晚。不是在每个循环上获取值,而是跟踪x
和y
:
var rect = document.getElementById('player');
var x = rect.getAttribute('x')*1,
y = rect.getAttribute('y')*1;
var pos_x = 0, pos_y = 0;
setInterval(move, 30);
function move(i)
{
pos_x++;
if (pos_x < 500){
rect.setAttribute('x', pos_x);
}
else {
pos_y +=10
pos_x = 0;
rect.setAttribute('x', pos_y);
rect.setAttribute('y', pos_y);
}
}