代碼鏈接:https://github.com/zhangKunUserGit/vue-component
效果圖:
大家可以在線運行: https://zhangkunusergit.github.io/vue-component/dist/btnRipple.html 看看效果(一定要狠狠的點擊哦)。
先說一下用法:
<zk-button class="btn btn-default">默認按鈕</zk-button> <zk-button class="btn btn-default btn-round">默認按鈕</zk-button> <zk-button class="btn btn-default btn-round" :speed="4" :opacity="0.6">定義速度和初始的波浪透明度</zk-button>
原理:
這里用的是canvas + requestAnimationFrame(兼容性可以網上找一下解決方法) 繪制的波紋,有些用的是css transform + setTimeout做的,我感覺不太好。
模板(template):
<template> <button class="zk-btn"> <canvas class="zk-ripple" @click="ripple"></canvas> <slot></slot> </button> </template>
點擊代碼如下(我已經加入詳細的注釋)
ripple(event) { // 清除上次沒有執行的動畫 if (this.timer) { window.cancelAnimationFrame(this.timer); } this.el = event.target; // 執行初始化 if (!this.initialized) { this.initialized = true; this.init(this.el); } this.radius = 0; // 點擊坐標原點 this.origin.x = event.offsetX; this.origin.y = event.offsetY; this.context.clearRect(0, 0, this.el.width, this.el.height); this.el.style.opacity = this.opacity; this.draw(); },
這里主要初始化canvas和獲取用戶點擊的位置坐標,並開始繪制。
循環繪制
draw() { this.context.beginPath(); // 繪制波紋 this.context.arc(this.origin.x, this.origin.y, this.radius, 0, 2 * Math.PI, false); this.context.fillStyle = this.color; this.context.fill(); // 定義下次的繪制半徑和透明度 this.radius += this.speed; this.el.style.opacity -= this.speedOpacity; // 通過判斷半徑小於元素寬度或者還有透明度,不斷繪制圓形 if (this.radius < this.el.width || this.el.style.opacity > 0) { this.timer = window.requestAnimationFrame(this.draw); } else { // 清除畫布 this.context.clearRect(0, 0, this.el.width, this.el.height); this.el.style.opacity = 0; } }
總結:
上面代碼我沒有復制完整,大家想看源碼可以下載看一下
這是4月最后一天上班了,5.1要好好休息一下。