Sitemap

How to make your cursor into an image using JavaScript

3 min readNov 9, 2017

--

I was inspired by this cute little ladybug to make a game you can play in your browser. I had this idea that flowers would randomly grow in the window and your cursor would be a little bee that could fly around gathering nectar and pollinating them. And hey, maybe it could even bring some awareness to the whole colony collapse issue… (hashtag savethebees.)

Markup for the field, bee image and flowers

So how do we go about making an image follow the user’s cursor? I started, as I always do, by googling. I read a few posts on Stack Overflow, then searched around on Codepen for a while. I found a few examples and copy/pasted some code until I found one that was simple enough to figure out what was going on. Then it was time to start my own project!

First I made a <div> with id of ‘field’ that would take up the whole screen by giving it a height:100vh and width: 100% in my css file. I also made the background green to simulate grass. Then I made an image tag with the id of ‘bee’ and downloaded a little clipart bee (in png form so the background is transparent). I set the bee to position:absolute so that we can tell the bee where to be on the field using the top and left properties. I used document.getElementById() to set the bee to a variable in my JavaScript. I also used getElementById() to select the field so I could use .onmousemove to call a function that would be triggered every time the mouse moves over the field.

Tracking mouse movement and setting bee image to position of cursor

The function uses two variables, xPosition and yPosition which are set to the current x and y position of the the cursor. Finally, we style the bee to appear wherever the cursor is (bee.style.left = xPosition; bee.style.top = yPosition;) For the final touch, I set cursor: none in the css so you can’t see the usual cursor arrow, only the image of the friendly bee.

I did run into an interesting bug (haha!) when I tried to use my new bee cursor to click on things. It turns out that if you set the x and y position to exactly those of the cursor, sometimes the cursor is actually clicking on the bee image instead of whatever is underneath that. So I changed my code slightly to add one pixel to whatever the y position is, that way the cursor is just slightly off of the bee image. I used my bee to make this game, but I hope this inspires you to create your own custom cursor image!

Added some enemies to make the game more difficult!

--

--

Amie Everett
Amie Everett

Written by Amie Everett

Hi! I’m a web developer. I’m starting this blog to document my progress and hopefully help out some other people too! (Headshot by Pam Lau)

Responses (1)