当前位置:首页 > canvas绘制一个加载中的动画

canvas绘制一个加载中的动画

发布于 2018-07-16 阅读 717 次 Canvas Javascript

介绍:

一个canvas绘制的水波效果的正在加载动画效果。颜色随机设置的;每次进来颜色都不一样。

预览:

loading预览

使用方式

  1. window.onload = function(){
  2. var l = new LoadAnim({id: 'canvas'});
  3. l.init();
  4. }

源代码

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. <style>
  7. body,html,canvas{padding:0;margin:0;}
  8. canvas{display:block;}
  9. </style>
  10. </head>
  11. <body>
  12. <canvas id='canvas'>您的浏览器不支持</canvas>
  13. </body>
  14. </html>
  15. <script>
  16. function LoadAnim(opt){
  17. this.circles = []; //圆半径
  18. this.w = window.innerWidth,
  19. this.h = window.innerHeight;
  20. this.num = opt.num?opt.num:5; // 圆形的数量
  21. this.dis = opt.dis?opt.dis:1; //加速度
  22. this.rgb = opt.rgb?opt.rgb:'';
  23. this.el = document.getElementById(opt.id);
  24. this.ctx = this.el.getContext('2d');
  25. this.el.width = this.w;
  26. this.el.height = this.h;
  27. this.r = opt.r?opt.r:this.w/5;
  28. }
  29. LoadAnim.prototype.init = function(){
  30. this.makeCircles();
  31. this.loop();
  32. }
  33. LoadAnim.prototype.makeCircles = function(){
  34. this.rgb = this.rgb?this.rgb:getRandColor();
  35. for(var i=this.num;i>-1;i--){
  36. var c = {
  37. r: this.r/this.num*i,
  38. alpha:(1/this.r) * this.r/this.num
  39. };
  40. this.circles.push(c)
  41. }
  42. }
  43. LoadAnim.prototype.drawCircle = function(){
  44. for(var i=0;i<this.num+1;i++){
  45. this.ctx.beginPath();
  46. this.ctx.fillStyle = "rgba("+this.rgb.r+","+this.rgb.g+","+this.rgb.b+","+this.circles[i].alpha+")";
  47. this.ctx.arc(this.w/2, this.h/2, this.circles[i].r, 0, 2*Math.PI);
  48. this.ctx.fill();
  49. }
  50. }
  51. LoadAnim.prototype.loop = function(){
  52. var _this = this;
  53. window.requestAnimationFrame(function(){_this.loop();});
  54. this.ctx.clearRect(0, 0, this.w, this.h);
  55. this.drawCircle(this.rgb);
  56. for(var i=0;i<this.num+1;i++){
  57. if(this.circles[i].r > this.r){
  58. this.circles.splice(i, 1);
  59. this.circles.push({r: 0, alpha:0});
  60. } else {
  61. this.circles[i].r += this.dis;
  62. this.circles[i].alpha = 1 - (1/this.r) * this.circles[i].r;
  63. }
  64. }
  65. }
  66. function getRandom(min, max){
  67. return Math.floor((max-min)*Math.random() + min);
  68. }
  69. function getRandColor(){
  70. var r = getRandom(0, 255),
  71. g = getRandom(0, 255),
  72. b = getRandom(0, 255);
  73. var rgb = {
  74. r: r,
  75. g: g,
  76. b: b
  77. }
  78. return rgb;
  79. }
  80. window.onload = function(){
  81. var l = new LoadAnim({id: 'canvas'});
  82. l.init();
  83. }
  84. </script>