radial gradient at mouse position in javascript

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:

  1. Create an event listener for the mousemove event on the canvas.
  2. In the event handler function, get the current mouse position relative to the canvas.
  3. Use the canvas 2D context to create a new radial gradient object.
  4. Set the gradient's center point to be the current mouse position.
  5. Set the gradient's radius to be some appropriate value.
  6. Set any additional color stops and other gradient properties as desired.
  7. Use the 2D context's fillStyle property to set the fill style to be the radial gradient.
  8. 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 element
const canvas = document.querySelector('canvas');

// Attach a mousemove event listener to the canvas
canvas.addEventListener('mousemove', handleMouseMove);

// Event handler function for mousemove events
function handleMouseMove(event) {
  // Get the current mouse position relative to the canvas
  const rect = canvas.getBoundingClientRect();
  const mouseX = event.clientX - rect.left;
  const mouseY = event.clientY - rect.top;

  // Create a new radial gradient object
  const 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);
}
976 chars
28 lines

gistlibby LogSnag