I've designed a spotlight effect with css, html and java. This is the link to the page: https://civitonia.com/ The spotlight follows the cursor, but as you can see, when you refresh the page or when you open it, the spotlight is not center on the page but you can see it a the bottom right. I'd like to set a "center point" or something similar that send the spotlight effect at the center of the page every time I refresh it/open it. Is it possible?
CSS:
.spotlight {
position: fixed;
width: 100%;
height: 100%;
pointer-events: none;
background-image: radial gradient(circle, transparent 160px, rgba(0, 0, 0, 0)
200px);
}
SCRIPT:
<script>
window.addEventListener("DOMContentLoaded", () => {
const spotlight = document.querySelector('.spotlight');
let spotlightSize = 'transparent 160px, rgba(0, 0, 0, 0.85) 200px)';
window.addEventListener('mousemove', e => updateSpotlight(e));
function updateSpotlight(e) {
spotlight.style.backgroundImage = `radial-gradient(circle at ${e.pageX / window.innerWidth * 100}% ${e.pageY / window.innerHeight * 100}%, ${spotlightSize}`;
}
});
</script>
CodePudding user response:
You can set spotlight to center by setting its radial gradient at half of window's innerWidth
and innerHeight
on "DOMContentLoaded"
.
window.addEventListener("DOMContentLoaded", () => {
const spotlight = document.querySelector('.spotlight');
let spotlightSize = 'transparent 160px, rgba(0, 0, 0, 0.85) 200px)';
spotlight.style.backgroundImage = `radial-gradient(circle at ${window.innerWidth/2}px ${window.innerHeight/2}px, ${spotlightSize}`;
window.addEventListener('mousemove', e => updateSpotlight(e));
function updateSpotlight(e) {
spotlight.style.backgroundImage = `radial-gradient(circle at ${e.pageX / window.innerWidth * 100}% ${e.pageY / window.innerHeight * 100}%, ${spotlightSize}`;
}
});
Snippet:
window.addEventListener("DOMContentLoaded", () => {
const spotlight = document.querySelector('.spotlight');
let spotlightSize = 'transparent 160px, rgba(0, 0, 0, 0.85) 200px)';
spotlight.style.backgroundImage = `radial-gradient(circle at ${window.innerWidth/2}px ${window.innerHeight/2}px, ${spotlightSize}`;
window.addEventListener('mousemove', e => updateSpotlight(e));
function updateSpotlight(e) {
spotlight.style.backgroundImage = `radial-gradient(circle at ${e.pageX / window.innerWidth * 100}% ${e.pageY / window.innerHeight * 100}%, ${spotlightSize}`;
}
});
.spotlight {
position: fixed;
width: 100%;
height: 100%;
pointer-events: none;
background-image: radial-gradient(circle, transparent 160px, rgba(0, 0, 0, 0) 200px);
}
<div ></div>