【问题标题】:Raphael transform object diagonally and infinite setIntervals拉斐尔对角变换对象和无限setIntervals
【发布时间】:2013-05-15 02:24:06
【问题描述】:

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

另一个问题是我的 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

【问题讨论】:

  • 使用 setInterval 为某些东西设置动画是一种糟糕的方法。在 Raphael 中,我们可以利用 Element.animate() 方法,还有很多额外的优势。

标签: javascript loops animation raphael transform


【解决方案1】:

我将“向上”功能修改为下面的那个

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

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

【讨论】:

  • 对 transform 属性进行动画处理是正确的,比动画 cx 和 cy 属性更好更快。在拖动开始和移动处理程序中也必须考虑到这一点,以保持一致。这样,getBBox 将使用 true 参数调用。
  • 嗨,一个简单的问题。我选择 setInterval 方法的原因是因为我需要一条路径来跟随它。除了圆圈回来时,我的大部分路径都在工作。你认为他们是找到这个的方法吗? jsfiddle.net/roflcopterofl/Uznp2
【解决方案2】:

如果圆圈需要在拖动后回到初始位置,我们可以通过使用 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');
};

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多