【问题标题】:Animated circle using canvas with numbers counting up使用带有数字计数的画布的动画圆圈
【发布时间】:2014-06-09 10:27:45
【问题描述】:

以下 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();

【问题讨论】:

  • 你想让数字根据百分比上下浮动吗?
  • 我希望图形不仅上下而且左右,以便它始终靠近填充圆/线的尖端/末端(例如绿色圆圈)。如果还是不清楚我就画个图。我现在认为必须有一种方法可以通过使用以实心圆的辐射作为输入的公式来计算图形必须出现的位置,所以我现在正在尝试。

标签: animation canvas html5-canvas


【解决方案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';

计算一个位置,demo 显示文本在里面 - 对于外面(或在弧的中间)只需调整 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

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多