JS点击按钮实现水波纹效果是一种很炫酷的UI效果,可以为网站增加动态和交互的效果,本文将详细讲解实现这种效果的完整攻略。实现方法有两种,分别是使用CSS3和使用Canvas。
CSS3 实现 js 点击按钮水波纹效果
HTML 结构
首先需要在HTML文件中添加一个按钮,如下所示:
<button class="wave-button">Button</button>
CSS 样式
需要设置.wave-button
按钮的样式。这里使用伪类:before
和:after
为按钮添加水波纹效果。
.wave-button {
background-color: blue;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
position: relative;
overflow: hidden;
}
.wave-button:hover:before,
.wave-button:focus:before {
content: "";
display: block;
position: absolute;
z-index: 1;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 0;
height: 0;
border-radius: 100%;
background-color: rgba(255, 255, 255, 0.5);
animation: wave 0.8s linear;
}
@keyframes wave {
from {
width: 0;
height: 0;
opacity: 0.5;
}
to {
width: 300px;
height: 300px;
opacity: 0;
}
}
JS 代码
当按钮被点击时,调用以下JavaScript代码:
document.querySelector('.wave-button').addEventListener('click', function (event) {
const button = event.target;
const wave = button.querySelector('.wave');
const buttonPos = button.getBoundingClientRect();
if (wave) {
wave.remove();
}
const posX = event.clientX - buttonPos.left;
const posY = event.clientY - buttonPos.top;
const ripple = document.createElement('span');
ripple.classList.add('wave');
ripple.style.top = `${posY}px`;
ripple.style.left = `${posX}px`;
button.appendChild(ripple);
setTimeout(() => {
ripple.remove();
}, 800);
});
Canvas 实现 js 点击按钮水波纹效果
HTML 结构
与CSS3实现方式一样,需要在HTML文件中添加一个按钮,如下所示:
<button class="wave-button">Button</button>
JS 代码
先创建画布和配置:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = canvas.height = 100;
canvas.classList.add('wave-canvas');
document.querySelector('.wave-button').appendChild(canvas);
const circle = {
x: 0,
y: 0,
width: 0,
height: 0,
lineWidth: 3,
alpha: 0.5,
strokeStyle: '#ffffff',
};
为按钮添加事件监听器,在事件触发时绘制水波纹:
document.querySelector('.wave-button').addEventListener('click', function (event) {
const button = event.target;
const buttonPos = button.getBoundingClientRect();
circle.x = event.clientX - buttonPos.left - canvas.width / 2;
circle.y = event.clientY - buttonPos.top - canvas.width / 2;
// 绘制水波纹
const wave = setInterval(() => {
circle.width += 3;
circle.height += 3;
circle.alpha -= 0.02;
circle.lineWidth -= 0.03;
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.width, 0, 2 * Math.PI);
ctx.lineWidth = circle.lineWidth;
ctx.globalAlpha = circle.alpha;
ctx.strokeStyle = circle.strokeStyle;
ctx.stroke();
if (circle.alpha <= 0) {
clearInterval(wave);
waveEnd();
}
}, 30);
});
function waveEnd() {
// 恢复初始值
circle.width = 0;
circle.height = 0;
circle.alpha = 0.5;
circle.lineWidth = 3;
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
两种实现方式都可以让按钮实现水波纹效果,选择使用哪种方法需要根据实际情况进行考虑。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:js点击按钮实现水波纹效果代码(CSS3和Canves) - Python技术站