To create a radial gradient at the mouse position in JavaScript, we can use the HTML5 canvas element and its associated 2D context. The basic steps are as follows:
Create an event listener for the mousemove event on the canvas.
In the event handler function, get the current mouse position relative to the canvas.
Use the canvas 2D context to create a new radial gradient object.
Set the gradient's center point to be the current mouse position.
Set the gradient's radius to be some appropriate value.
Set any additional color stops and other gradient properties as desired.
Use the 2D context's fillStyle property to set the fill style to be the radial gradient.
Use the 2D context's fillRect method to fill the canvas with the gradient.
Here's an example implementation:
index.tsx
// Get a reference to the canvas elementconst canvas = document.querySelector('canvas');
// Attach a mousemove event listener to the canvascanvas.addEventListener('mousemove', handleMouseMove);
// Event handler function for mousemove eventsfunctionhandleMouseMove(event) {
// Get the current mouse position relative to the canvasconst rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
// Create a new radial gradient objectconst gradient = canvas.getContext('2d').createRadialGradient(mouseX, mouseY, 0, mouseX, mouseY, 100);
// Set the gradient color stops gradient.addColorStop(0, 'red');
gradient.addColorStop(0.5, 'green');
gradient.addColorStop(1, 'blue');
// Set the canvas fill style to be the gradient canvas.getContext('2d').fillStyle = gradient;
// Fill the canvas with the gradient canvas.getContext('2d').fillRect(0, 0, canvas.width, canvas.height);
}