使用CSS的clip-path属性实现图片探照灯效果
今天在这个网站上看到了一篇文章,使用CSS的clip-path属性实现的手电筒的特效,觉得非常赞,于是自己也模仿了一下。
代码演示
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> .bottomBg { --topX: 0; --topY: 0; --radius: 0; width: 720px; height: 911px; background-image: url('./2.jpg'); } .upBg { width: 100%; height: 100%; background-image: url('./3.jpg'); clip-path: circle(var(--radius) at var(--topX) var(--topY)); pointer-events: none; } </style> </head> <body> <div class="bottomBg" id="bottomBg"> <div class="upBg"></div> </div> <script> const bottomBg = document.getElementById('bottomBg'); function handleMouseMove(event) { const bounding = bottomBg.getBoundingClientRect(); const [x, y] = [event.clientX - bounding.left, event.clientY - bounding.top]; bottomBg.style.setProperty('--topX', `${ x }px`); bottomBg.style.setProperty('--topY', `${ y }px`); } function handleMouseOver(event) { handleMouseMove(event); bottomBg.style.setProperty('--radius', '120px'); } document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseover', handleMouseOver, { once: true }); </script> </body> </html>