如何在HTML中实现图像局部模糊与鼠标悬停局部清晰效果?
Perfect, I’ve got a solid solution for that local clear-on-hover background effect you’re trying to replicate (just like Canva’s homepage). Let’s break this down step by step—we’ll use a combo of CSS masks, filters, and JavaScript to track your mouse and reveal a sharp area right under the cursor:
1. HTML Structure
First, set up your background container with the image inside. We’ll use this container to layer the blurred overlay and track mouse movement:
<div id="background"> <img src="your-background-image.jpg" alt="Website Background"> </div>
2. CSS Styling
We’ll create a blurred overlay using a pseudo-element, then use a mask to "cut out" a clear area that follows your mouse. Here’s the CSS:
#background { position: absolute; top: 0; left: 0; z-index: -1; width: 100vw; height: 100vh; overflow: hidden; } #background img { width: 100%; height: 100%; object-fit: cover; /* Ensures image scales properly without distortion */ } #background::before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: inherit; /* Inherits the image from the parent container */ filter: blur(8px); /* Adjust this value to match Canva's blur intensity */ /* Initial mask: tiny transparent circle so the whole image is blurred by default */ mask: radial-gradient(circle 0px at center, transparent 100%, black 100%); -webkit-mask: radial-gradient(circle 0px at center, transparent 100%, black 100%); /* For Safari support */ transition: mask-position 0.1s ease; /* Smooths the cursor-following movement */ }
3. JavaScript for Mouse Tracking
Now we’ll add code to update the mask’s position as your mouse moves, revealing the clear area under the cursor:
const backgroundContainer = document.getElementById('background'); // Track mouse movement backgroundContainer.addEventListener('mousemove', (event) => { const mouseX = event.clientX; const mouseY = event.clientY; // Update the mask to create a clear circle at the mouse position const maskStyle = `radial-gradient(circle 150px at ${mouseX}px ${mouseY}px, transparent 100%, black 100%)`; backgroundContainer.style.mask = maskStyle; backgroundContainer.style.webkitMask = maskStyle; // For Safari }); // Reset mask when mouse leaves the background area backgroundContainer.addEventListener('mouseleave', () => { const resetMask = 'radial-gradient(circle 0px at center, transparent 100%, black 100%)'; backgroundContainer.style.mask = resetMask; backgroundContainer.style.webkitMask = resetMask; });
Key Notes to Tweak for Exact Canva Match
- Adjust the
blur(8px)value to make the background more or less blurred. - Change
circle 150pxto resize the clear area under your mouse (Canva uses a relatively large, soft-edged circle). - Ensure your background image is high-resolution to avoid pixelation when the clear area is revealed.
内容的提问来源于stack exchange,提问作者Amateur_coder

