使用jQuery动画时在对象后绘制线条

时间:2013-12-18 09:05:33

标签: javascript jquery function jquery-animate

我有这个方块,每隔5秒动画到一个随机位置。我现在要做的是在广场移动后画一条线,所以我可以看到它已经去过的地方等等。任何想法我应该怎么做?非常感谢您的帮助,谢谢!

<div id="square" style="width:50px; height:50px; background:blue; position:relative;"/>

<script>
$(document).ready(function(){
  setInterval(function(){

    var posx = Math.floor((Math.random()*1000)+1);
    var posy = Math.floor((Math.random()*1000)+1);

  $('#square').animate({ left:(posx*1), top: (posy*1) }, 3000);  

 },5000);
});

</script>

2 个答案:

答案 0 :(得分:2)

这是一个例子。它不漂亮,但应该让你开始。

http://jsfiddle.net/9gcXN/

HTML

<canvas width="500" height="500" id="mycanvas" style="position: absolute; left: 0px; top: 0px;"></canvas>
<div id="square" style="width:50px; height:50px; background:blue; position: absolute;"></div>

JS

canvas = document.getElementById('mycanvas');
ctx = canvas.getContext('2d');

$(document).ready(function() {
var posx,posy,lastx,lasty = 0;

    setInterval(function(){
    lastx = posx;
    lasty = posy;

    posx = Math.floor((Math.random()*100)+1);
    posy = Math.floor((Math.random()*100)+1);

        $('#square').animate({ left:(posx*1), top: (posy*1) }, 3000, function() {
        ctx.beginPath();
ctx.moveTo(lastx,lasty);
ctx.lineTo(posx,posy);
ctx.stroke();

        });  

},3000);
});

希望它有所帮助!

答案 1 :(得分:1)

您可以使用step function for jQuery.animate()

(文档)$。就绪(函数(){   的setInterval(函数(){

var posx = Math.floor((Math.random()*1000)+1);
var posy = Math.floor((Math.random()*1000)+1);

  $('#square').animate({ left:(posx*1), top: (posy*1) }, {
      duration: 3000,
      step: function (now, tween) {
          var elemOffset = $(tween.elem).offset();
          $('<div class="a"></div>').css({top: elemOffset.top, left: elemOffset.left}).appendTo('body');
      }
  });  

},5000); });

关于jsfiddle的例子:

http://jsfiddle.net/g7xGy/