CODE CENTER

Trail Cursor

The code here creates an effect like you can see here.


HTML

Nothing of particular note here, just that YOUR_CSS, YOUR_JS, and YOUR_CURSOR_IMAGE are to be filled in appropriately, and CANVAS_ID and IMAGE_ID can be any name as long as you use the same name in other files.

In order for us to use js to draw an image, the image needs to exist on the page; however it doesn't need to be visible, hence the img tag with display:none.


CSS

Important details to note here include pointer-events:none, z-index:100, and position:fixed. There are comments in the css to explain them.


JS

All the const values at the top are values you can adjust to change the behavior of your cursor. The code is commented to explain what each part does, but I'll go over some important details.

In order to make a cursor trail work, we need to store a set of coordinates to define where each "link" in the trail will be drawn. That is stored in the "cursors" value.

From there, every step of the animation, we need to move each cursor a fraction of the way to the next link in the chain, eventually moving the last link a fraction of the way to the cursor's current position. This is handled by the "trailCursors()" function.

After that, we simply draw all the cursors to the screen! We use a little math to set different alpha values to the cursor; but all we need to do is run through our list of cursor coordinates and draw the image to each of those locations. This is handled by the "drawCursors()" function.


Back to Code Center.