使用帆布的动画圈子与数字计数

时间:2014-04-24 08:32:34

标签: animation canvas html5-canvas

以下jsFiddle http://jsfiddle.net/QsMVn/6/包含动画圆圈以及显示已填充圆圈数量的百分比。我的目标是将百分比设置为动画,以便它们与它的末尾旁边的线一起移动。我无法弄清楚如何做到这一点。

jsFiddle代码:

    // requestAnimationFrame Shim
(function() {
  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                              window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();


var canvas = document.getElementById('myCanvas');
 var context = canvas.getContext('2d');
 var x = canvas.width / 2;
 var y = canvas.height / 2;
 var radius = 75;
 var endPercent = 85;
 var curPerc = 0;
 var counterClockwise = false;
 var circ = Math.PI * 2;
 var quart = Math.PI / 2;

 context.lineWidth = 10;
 context.strokeStyle = '#ad2323';
 context.shadowOffsetX = 0;
 context.shadowOffsetY = 0;
 context.shadowBlur = 10;
 context.shadowColor = '#656565';


 function animate(current) {
     context.clearRect(0, 0, canvas.width, canvas.height);
     context.beginPath();
     context.arc(x, y, radius, -(quart), ((circ) * current) - quart, false);
     context.stroke();
     curPerc++;
     if (curPerc < endPercent) {
         requestAnimationFrame(function () {
             animate(curPerc / 100);
         });
     }
 }

 animate();

1 个答案:

答案 0 :(得分:1)

您只需使用您拥有的角度(以弧度表示)并根据该角度计算距离。

先决条件:更改上面几行,以便重复使用弧度:

var radians = (degrees - 90) * Math.PI / 180;  // subtract 90 here
...
ctx.arc(W / 2, H / 2, W / 3, 0 - 90 * Math.PI / 180, radians, false);

然后使用textAlign和textBaseline将文本居中:

ctx.textAlign = 'center';
ctx.textBaseline = 'middle';

计算一个位置,演示在内部显示文本 - 对于外部(或在弧的中间)只需调整dist值:

var dist = W / 3 - 40;
var tx = W * 0.5 + dist * Math.cos(radians);
var ty = H * 0.5 + dist * Math.sin(radians);
ctx.fillText(text, tx, ty);

<强> Modified fiddle here

希望这有帮助!