【问题标题】:can I animate an arc's end angle?我可以为弧的结束角度设置动画吗?
【发布时间】:2012-12-02 19:12:57
【问题描述】:

我正在尝试使我的圆弧的结束角度从 X 变为 Y。

这是我所拥有的:http://jsfiddle.net/97dUJ/

我可以做吗:

var endAngle = 0 * Math.PI;

动画到:

var endAngle = 0.5 * Math.PI;

不只是跳到那个角度,而且实际上是动画,很简单,比如 easeInOut 之类的......这可能吗?谢谢!

【问题讨论】:

  • 尝试使用新的requestAnimationFrame() 东西,在每帧渲染后在旧的弧线上重画一条稍长的弧线。这是一个相关链接:paulirish.com/2011/requestanimationframe-for-smart-animating
  • 我对 HTML5 还是很陌生,知道如何采用这种方法并将其应用于小提琴吗?谢谢!
  • 我假设您这样做是出于教育目的,但如果您是为商业项目而工作(并且为了其他可能阅读本文的人的利益),我强烈建议您这样做查看 D3 (d3js.org),因为它会为您完成所有繁重的工作,让您专注于最终结果。学习愉快!
  • 您可以尝试使用 Raphael 库(是的,它有我的名字)。这是另一个可能会引导您前进的问题:stackoverflow.com/q/9361476/1661358

标签: javascript html animation canvas html5-canvas


【解决方案1】:

您可以为 endAngle 属性设置动画,然后清除画布并使用最新值重新绘制弧线,就像这样......

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var props = {
    x : canvas.width / 2,
    y : canvas.height / 2,
    radius : 75,
    startAngle : 0,
    endAngle : 0,
    counterClockwise : false
}

function drawArc() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.beginPath();
    context.arc(props.x, props.y, props.radius, props.startAngle, props.endAngle, props.counterClockwise);
    context.lineWidth = 15;

    // line color
    context.strokeStyle = 'black';
    context.stroke();    
}

TweenMax.to(props, 1, {endAngle: Math.PI * 2, yoyo:true, repeat:-1, ease:Quad.easeInOut, onUpdate:drawArc});

http://jsfiddle.net/B8XCw/8/

注意:这是使用 Tweenmax 为属性设置动画

【讨论】:

    【解决方案2】:

    这很容易做到,你只需要添加一个setTimeoutrequestAnimationFrame 并增加你想要乘以结束角度的值。

    Live Demo

     var canvas = document.getElementById('myCanvas');
          var context = canvas.getContext('2d');
          var x = canvas.width / 2;
          var y = canvas.height / 2;
          var radius = 75;
          var startAngle = 1.5 * Math.PI;
          var curVal = 0;
          var endAngle = 0 * Math.PI;
          var counterClockwise = false;
    
    function animate(){
        if(curVal < 0.5){
          curVal+= 0.01;
        }
          endAngle = curVal * Math.PI;
          context.beginPath();
          context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
          context.lineWidth = 15;
          // line color
          context.strokeStyle = 'black';
          context.stroke();
        setTimeout(animate,30);
    }
    
    animate();
    ​
    

    【讨论】:

    • 这是一个很好的例子,只需要在动画完成后停止函数运行。这是添加 if(curVal
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2012-03-08
    • 2019-08-30
    相关资源
    最近更新 更多