Raphael变换对象对角和无限setIntervals

时间:2013-05-15 02:24:07

标签: javascript loops animation raphael transform

我正在制作一个小动画,用户拖动一个圆圈,圆圈返回起点。我找到了让圆圈回到起点的方法。唯一的问题是它会在返回之前击中框架的一侧。是否可以直接返回(沿着形状和起点之间绘制的线的路径)。

另一个问题是我的setInterval不想停止。如果您尝试再次拉动它,它会在释放鼠标之前将其拉回。它似乎每次都会加速。我已经尝试使用带有计时器的while循环,但结果不是那么好。这可以解决吗?

    var paper = Raphael(0, 0, 320, 200);
    //var path = paper.path("M10 10L40 40").attr({stoke:'#000000'});
    //var pathArray = path.attr("path");
    var circle = paper.circle(50, 50, 20);
    var newX;
    var newY;
    circle.attr("fill", "#f00");
    circle.attr("stroke", "#fff");



     var start = function () {
        this.attr({cx: 50, cy: 50});
        this.cx = this.attr("cx"),
        this.cy = this.attr("cy");
     },
     move = function (dx, dy) {
        var X = this.cx + dx,
        Y = this.cy + dy;
        this.attr({cx: X, cy: Y});
     },

     up = function () {
        setInterval(function () {
    if(circle.attr('cx') > 50){
        circle.attr({cx : (circle.attr('cx') - 1)});
    } else if (circle.attr('cx') < 50){
        circle.attr({cx : (circle.attr('cx') + 1)});
    } 

    if(circle.attr('cy') > 50){
        circle.attr({cy : (circle.attr('cy') - 1)});
    } else if (circle.attr('cy') < 50){
        circle.attr({cy : (circle.attr('cy') + 1)});
    } 
   path.attr({path: pathArray});
},2);
 };

circle.drag(移动,开始,向上);

这是Jfiddle:http://jsfiddle.net/Uznp2/

非常感谢:D

2 个答案:

答案 0 :(得分:0)

我将“up”功能修改为

下面的功能
up = function () {
  //starting x, y of circle to go back to
  var interval = 1000;
  var startingPointX = 50;
  var startingPointY = 50;
  var centerX = this.getBBox().x + (this.attr("r")/2);
  var centerY = this.getBBox().y + (this.attr("r")/2);
  var transX = (centerX - startingPointX) * -1;
  var transY = (centerY - startingPointY) * -1;
  this.animate({transform: "...T"+transX+", "+transY}, interval);
};

和“开始”功能如下:

var start = function () {
  this.cx = this.attr("cx"),
  this.cy = this.attr("cy");
}

这是您正在寻找的行为吗?对不起,如果我误解了这个问题。

答案 1 :(得分:0)

如果圆圈需要在拖动后返回到初始位置,我们可以通过使用transform属性的简单动画来实现。

// Assuming that (50,50) is the location the circle prior to drag-move (as seen in the code provided)
// The animation is set to execute in 1000 milliseconds, using the easing function of 'easeIn'.
up = function () {
   circle.animate({transform: 'T50,50'}, 1000, 'easeIn');
};

希望这有帮助。