使用 jQuery animate 时绘制一个又一个对象的线条

Drawing line after object while using jQuery animate

本文关键字:一个 一个对象 animate jQuery 绘制 使用      更新时间:2023-09-26

我有这个正方形,它每 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>

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

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);
});

希望对您有所帮助!

你可以对 jQuery.animate() 使用一个 step 函数。

$(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) }, {
      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/