Animate a Canvas circle to draw on load

前提是你 提交于 2019-11-29 00:16:56

Live Demo

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

Basically I used the same formula from the demo link you posted. I then added an animation function that when called will update the circle until it reaches the desired ending percent.

The animation is continually called by requestAnimationFrame this is the preferred way of doing any kind of animations with canvas. Every time animate is called the current percent is increased by one, which is then used to redraw the arc.

Three steps:

1) Make an "init" function which will assign the variables (they aren't in any   
function).  
2) Then use requestAnimationFrame, or setInterval with your   
drawing function you will create.  
3) In this "drawing/updating" function you're going to   
write your code to do the maths and then just animate the updated circle.    

There aren't any functions in your code. If you don't know how to make functions and use them + what is global variable it's better to read first a tutorials about that but anyway I'll try to make you an example :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!