Snake Like Effect using CSS and JavaScript
Last Updated :
15 Feb, 2023
In this article, we will see how to create a Snake Like Effect by using CSS and JavaScript.
CDN Link: Include the following GSAP library in your HTML code.
<script src=”https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js”></script>
Approach :
- We have taken a div tag named snake which is an instance of the full snake. We have taken circle, we can take another shape by using simple CSS.
- We have created more divs to give the length of the snake. We can include more div tags to increase its length.
- document.body.addEventListener(“mousemove”): This function in JavaScript attaches a moving mouse event to the document. When the user moves the mouse pointer anywhere in the document, the event which is being mentioned occurs.
- e.clientX: Get the horizontal coordinate.
- e.clientY: Get the vertical coordinate.
- stagger :For delay in animation (0.05 sec), we can see the snake.
- gsap.to(“.snake”): It will track the snake with reference to pointer coordinates.
Example:
HTML
<!DOCTYPE html>
< html >
< head >
< style type = "text/css" >
/* Area part for snake */
</ style >
</ head >
< body >
< div class = "area" >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
< div class = "snake" ></ div >
</ div >
< script
</ script >
< script type = "text/javascript" >
document.body.addEventListener("mousemove", e => {
gsap.to(".snake", {
x : e.clientX,
y : e.clientY,
stagger : -0.05,
})
})
</ script >
</ body >
</ html >
|
CSS
.area {
width : 80px ;
height : 80px ;
position : relative ;
}
.area .snake {
position : absolute ;
top : 0 ;
left : 0 ;
width : 100% ;
height : 100% ;
background : rgb ( 3 , 171 , 15 );
border : 2px solid white ;
border-radius: 50% ;
}
|
Output: Click here to see live code output
As you can see from the above output, we have created a snake that follows our mouse pointer making it look like a Snake-like effect.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...