Files
theme-zero-efects/parts/spotlight-cursor/spotlight-cursor.js
T

97 lines
2.7 KiB
JavaScript

/* Spotlight cursor from Cursify.
https://cursify.ui-layouts.com/components/spotlight-cursor */
(function () {
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
return;
}
var spotlightSize = 50;
var spotlightIntensity = 0.8;
var fadeSpeed = 0.1;
var glowColor = '255, 255, 255';
var pulseSpeed = 2000;
var root = document.createElement('div');
root.className = 'spotlight-cursor';
root.setAttribute('aria-hidden', 'true');
var canvas = document.createElement('canvas');
root.appendChild(canvas);
document.body.appendChild(root);
var ctx = canvas.getContext('2d');
var spotlightPos = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
var targetPos = { x: spotlightPos.x, y: spotlightPos.y };
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function lerp(start, end, factor) {
return start + (end - start) * factor;
}
function handleMouseMove(event) {
targetPos.x = event.clientX;
targetPos.y = event.clientY;
}
function render() {
spotlightPos.x = lerp(spotlightPos.x, targetPos.x, fadeSpeed);
spotlightPos.y = lerp(spotlightPos.y, targetPos.y, fadeSpeed);
ctx.globalCompositeOperation = 'source-over';
ctx.clearRect(0, 0, canvas.width, canvas.height);
// color de fondo
ctx.fillStyle = 'rgba(250, 250, 250, 0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
var pulseScale = 1 + 0.1 * Math.sin((Date.now() / pulseSpeed) * Math.PI * 2);
var currentSpotlightSize = spotlightSize * pulseScale;
var gradient = ctx.createRadialGradient(
spotlightPos.x,
spotlightPos.y,
0,
spotlightPos.x,
spotlightPos.y,
currentSpotlightSize
);
gradient.addColorStop(0, 'rgba(' + glowColor + ', ' + spotlightIntensity + ')');
gradient.addColorStop(0.5, 'rgba(' + glowColor + ', ' + (spotlightIntensity * 0.5) + ')');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(spotlightPos.x, spotlightPos.y, currentSpotlightSize, 0, Math.PI * 2);
ctx.fill();
ctx.globalCompositeOperation = 'source-over';
var glowGradient = ctx.createRadialGradient(
spotlightPos.x,
spotlightPos.y,
0,
spotlightPos.x,
spotlightPos.y,
currentSpotlightSize * 1.2
);
glowGradient.addColorStop(0, 'rgba(' + glowColor + ', 0.2)');
glowGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.fillStyle = glowGradient;
ctx.beginPath();
ctx.arc(spotlightPos.x, spotlightPos.y, currentSpotlightSize * 1.2, 0, Math.PI * 2);
ctx.fill();
window.requestAnimationFrame(render);
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
document.addEventListener('mousemove', handleMouseMove);
render();
}());