Raphael JS - 沿着它的路径动画半圆形

时间:2013-04-02 09:15:35

标签: javascript animation raphael

我有一个仪表/拨号类型级别可以在我的应用程序中设置动画。值和更改时,针和拨号将自动更新。我必须使用的代码可以进行小的更改,但是当它有更大的更改时,动画不会沿着半圆的路径运行。

我的代码是这样的:(间隔仅用于测试目的)

var rad = Math.PI / 180;
var getCurvePath = function(cx, cy, r, startAngle, endAngle) {
    var x1 = cx + r * Math.cos(-startAngle * rad),
        x2 = cx + r * Math.cos(-endAngle * rad),
        y1 = cy + r * Math.sin(-startAngle * rad),
        y2 = cy + r * Math.sin(-endAngle * rad);

    return ["M", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2];
};

var zeroAngle = 197, fullAngle = -15,baseAngle = 199,
    r = Raphael('level');

var level = r
    .path(getCurvePath(150, 150, 75, zeroAngle, baseAngle))
    .attr({
        'stroke': '#FF0000',
        'stroke-width': '11px'
    });

window.setInterval(function() {
    var ratio = Math.random();
    var newLevelAngle = (zeroAngle - fullAngle) * ratio;
    level.animate({
        'path': getCurvePath(150, 150, 75, newLevelAngle, baseAngle)
    }, 1000, 'bounce');
}, 2000);

我在这里设置了一个JS小提琴,所以你可以看到这个:http://jsfiddle.net/Rfd3v/1/

1 个答案:

答案 0 :(得分:0)

这里接受的答案解决了我的问题: drawing centered arcs in raphael js

我需要根据@ genkilabs的答案调整一些内容以适应水平/仪表应用。希望这可能对其他人有所帮助:

var arcCentre = { x: 100, y: 100 },
    arcRadius = 50,
    arcMin = 1, // stops the arc disappearing for 0 values
    baseRotation = -100, // this starts the arc from a different point
    circleRatio = 220/360, // I found this helpful as my arc is never a full circle
    maxValue = 1000; // arbitrary        

// starts the arc at the minimum value
var myArc = r.path()
         .attr({
             "stroke": "#f00",
             "stroke-width": 14,
             arc: [arcCentre.x, arcCentre.y, arcMin, 100, arcRadius],
         })
         .transform('r'+ baseRotation + ',' + arcCentre.x + ',' + arcCentre.y);

// set a new value
var newValue = 234; // pick your new value

// convert value to ratio of the arc to complete
var ratio = newValue / maxValue;

// set level
var newLevelValue = Math.max(arcMin, ratio * 100 * circleRatio);
myArc.animate({
    arc: [arcCentre.x, arcCentre.y, newLevelValue, 100, arcRadius]
}, 750, 'bounce');