mouse motion blur in javascript

To create a mouse motion blur effect in JavaScript, we first need to detect the mouse movement using a mouse event listener. We can then draw the previous frames of the canvas with decreased opacity to create a blur effect.

Here's a sample code:

index.tsx
// Initialize canvas
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

// Initialize variables
let mouseX = 0;
let mouseY = 0;

// Mouse move event listener
canvas.addEventListener('mousemove', (event) => {
  mouseX = event.clientX;
  mouseY = event.clientY;
});

// Draw function
function draw(timestamp) {
  // Clear canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw previous frames with decreased opacity
  ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // Draw current mouse position
  ctx.fillStyle = 'black';
  ctx.beginPath();
  ctx.arc(mouseX, mouseY, 10, 0, 2 * Math.PI, false);
  ctx.fill();

  // Request next frame
  window.requestAnimationFrame(draw);
}

// Start animation loop
window.requestAnimationFrame(draw);
836 chars
36 lines

In this code, we first initialize the canvas and variables for mouse position. We then add a mouse move event listener to update the mouse position variables. Inside the draw function, we first clear the canvas and then draw the previous frames with decreased opacity using the fillRect method. We then draw the current mouse position as a circle using the arc method. Finally, we request the next frame using the requestAnimationFrame method to create an animation loop.

By adjusting the opacity and size of the previous frames, we can create a motion blur effect.

gistlibby LogSnag