Frage

The following jsFiddle http://jsfiddle.net/QsMVn/6/ has animated circles and the percentage showing how much of the circle has been filled. My aim is to have the percentages animated as well so that they move along with the line right next to the end of it. I can't figure out how to do that.

Code of 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();
War es hilfreich?

Lösung

You just use the angle you have (in radians) and calculate a distance based on that.

Prerequisites: Change a couple of lines above so you can reuse the radians:

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

Then use textAlign and textBaseline to center the text:

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

Calculate a position, demo shows text on the inside - for outside (or in the middle of arc) just adjust the dist value:

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

Hope this helps!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top