代码链接:https://github.com/zhangKunUserGit/vue-component

效果图:

大家可以在线运行: https://zhangkunusergit.github.io/vue-component/dist/btnRipple.html 看看效果。

先说一下用法:

  1. <zk-button class="btn btn-default">默认按钮</zk-button>
  2. <zk-button class="btn btn-default btn-round">默认按钮</zk-button>
  3. <zk-button class="btn btn-default btn-round" :speed="4" :opacity="0.6">定义速度和初始的波浪透明度</zk-button>

原理:

这里用的是canvas + requestAnimationFrame(兼容性可以网上找一下解决方法) 绘制的波纹,有些用的是css transform + setTimeout做的,我感觉不太好。

模板(template):

  1. <template>
  2. <button class="zk-btn">
  3. <canvas class="zk-ripple" @click="ripple"></canvas>
  4. <slot></slot>
  5. </button>
  6. </template>

点击代码如下(我已经加入详细的注释)

  1. ripple(event) {
  2. // 清除上次没有执行的动画
  3. if (this.timer) {
  4. window.cancelAnimationFrame(this.timer);
  5. }
  6. this.el = event.target;
  7. // 执行初始化
  8. if (!this.initialized) {
  9. this.initialized = true;
  10. this.init(this.el);
  11. }
  12. this.radius = 0;
  13. // 点击坐标原点
  14. this.origin.x = event.offsetX;
  15. this.origin.y = event.offsetY;
  16. this.context.clearRect(0, 0, this.el.width, this.el.height);
  17. this.el.style.opacity = this.opacity;
  18. this.draw();
  19. },

这里主要初始化canvas和获取用户点击的位置坐标,并开始绘制。

循环绘制 

  1. draw() {
  2. this.context.beginPath();
  3. // 绘制波纹
  4. this.context.arc(this.origin.x, this.origin.y, this.radius, 0, 2 * Math.PI, false);
  5. this.context.fillStyle = this.color;
  6. this.context.fill();
  7. // 定义下次的绘制半径和透明度
  8. this.radius += this.speed;
  9. this.el.style.opacity -= this.speedOpacity;
  10. // 通过判断半径小于元素宽度或者还有透明度,不断绘制圆形
  11. if (this.radius < this.el.width || this.el.style.opacity > 0) {
  12. this.timer = window.requestAnimationFrame(this.draw);
  13. } else {
  14. // 清除画布
  15. this.context.clearRect(0, 0, this.el.width, this.el.height);
  16. this.el.style.opacity = 0;
  17. }
  18. }

总结:

上面代码我没有复制完整,大家想看源码可以下载看一下

这是4月最后一天上班了,5.1要好好休息一下。

 

版权声明:本文为zhangkunweb原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhangkunweb/p/vue_ripple.html