JavaScript code to create an image trail effect with your mouse
Mark E.
// Set the image source URL
var imageSrc = "path/to/image.png";
// Set the size of the image
var imageSize = 50;
// Create an array to store the images
var images = [];
// Create a function to initialize the images
function init() {
// Loop through the number of images
for (var i = 0; i < 10; i++) {
// Create a new image element
var img = document.createElement("img");
// Set the image source
img.src = imageSrc;
// Set the image size
img.style.width = imageSize + "px";
img.style.height = imageSize + "px";
// Set the image position to absolute
img.style.position = "absolute";
// Add the image to the array
images.push(img);
// Add the image to the document
document.body.appendChild(img);
}
}
// Create a function to update the images
function update() {
// Get the mouse position
var x = event.clientX;
var y = event.clientY;
// Loop through the images
for (var i = images.length - 1; i >= 1; i--) {
// Set the position of the current image to the position of the previous image
images[i].style.left = images[i-1].style.left;
images[i].style.top = images[i-1].style.top;
}
// Set the position of the first image to the mouse position
images[0].style.left = x - imageSize/2 + "px";
images[0].style.top = y - imageSize/2 + "px";
}
// Call the init function to create the images
init();
// Add an event listener to update the images on mouse move
document.addEventListener("mousemove", update);
This code creates an array of images that follow the mouse cursor, creating an image trail effect. The init()
function creates the images and adds them to the document, and the update()
function updates the position of each image on mouse move. The imageSrc
and imageSize
variables can be changed to use a different image or change the size of the image, respectively.