DEV Community

Cover image for Eyes follow the mouse pointer
Adrian
Adrian

Posted on • Updated on

Eyes follow the mouse pointer

Intro

Learn how to build the famous eyes that follow the mouse cursor.

It is an awesome effect that can be implemented easily in CodeGuppy with the help of a little bit of trigonometry.

What do you need?

To run the code in this article you don’t need to install anything on your local computer.

Just open the online JavaScript playground from codeguppy.com/code.html and copy and paste the following code in the integrated editor.

When ready, press the “Play” button to run the code.

Source code

// Use cartesian - polar coordinates conversion to implement
// eyes that follow mouse coursor

function loop()
{
    clear();

    drawEye(200, height / 2, 60);
    drawEye(380, height / 2, 60);
}


function drawEye(x, y, r)
{
    fill("white");
    ellipse(x, y, r * 2);

    drawEyePupil(x, y, 0.75 * r, 0.5 * r);
}

// Draw eyes that follow the mouse position
function drawEyePupil(x1, y1, r, pr)
{
    var angle = atan2(mouseY - y1, mouseX - x1);

    var x2 = x1 + r * cos(angle);
    var y2 = y1 + r * sin(angle);

    fill("black");
    ellipse(x2, y2, pr);
}

Feedback

If you liked the article, please follow @codeguppy on Twitter and / or visit codeguppy.com for more tutorials and projects.

Also, if you want to extend this article with detailed instructions explaing how to build the program step by step, please leave feedback in the comments.

Top comments (0)