Hey everyone. Welcome to today’s tutorial. In this tutorial I will show you how to create a colorful heart using JavaScript. It will look like the heart is floating the browser screen. The heart will never stop being created. We will display a message in the middle of the screen. I have written 'i love you' here. You can give it anything else.

To create this animation we will use HTML,CSS, and Javascript. We do not make use of any images, icons or external libraries and plugins to create this animation. This kind of complicated animation hardly finds application in real-world projects. However, they are a fun way to learn JavaScript. let's start lovers coding.

Create a heart

Before creating many hearts, you first need to know how to create a single heart. So first we will start by creating single heartthe.

Giving a heart structure to an HTML element using CSS can be difficult for beginners because they do not know about pseudo-elements. However, any structure of the element can be given using the CSS clip-path property. But here we will use the pseudo-elements.

HTML for heart shape:

Let us start by creating an element with class name ‘heart-shape.’ <div class="heart-shape"></div>. That is pretty much it for the HTML section.

CSS Styling the heart shape:

Now that we have created the heart, let us style it. We create a square by setting the height and width to 100 pixels. And use a red color as the background color of the square shape. Using a bright red color ensures a good contrast between the heart shape and the background of the webpage, thereby making the heart shape stand out.

Next, we want the heart to ALWAYS stay in the center of the webpage despite any scrolling. Therefore, we set the position attribute to the ‘absolute’ property. Also, we need to set the top and left attributes to 50% to position it in the center of the screen. We ‘center’ the ‘transform-origin’ property. Then rotated at a minus 45-degree angle using transform.

.heart-shape {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: rotate(-45deg) translate(-50%, -50%);
    transform-origin: center; 
}
Pseudo-Elements:

We now need two pseudo-elements, heart-shape:before and heart-shape:after. After combining these two shapes with the main div, we will get a heart shape.

To make both of them round, we need to give a border radius of 50%. We will also give the main div the same background color that we gave it. These are placed just above and to the right of the main div.

.heart-shape::before,
.heart-shape::after {
    content: "";
    position: absolute;
    background-color: red;
    width: 100%;
    height: 100%;
    border-radius: 50%;
}

It's placed minus 50% to the top of the main box (.heart-shape).

.heart-shape::before {
  top: -50%;
  left: 0;
}

It's placed 50% to the right of the main box (.heart-shape).

.heart-shape::after {
  top: 0;
  left: 50%;
}

Example The Heart Shape:

Here you look at it with the help of a small example.

The image above shows that a heart shape can be drawn with three different shapes.

The green border square shape you see in the image above is the main div element (heart-shaped). It's rotated at a 45-degree angle using transform. The black and blue colored border round shapes are the pseudo-elements (:before and :after).

The round shape with a black border is the ":before" element that has been set to the top minus (-) 50 percent and left 0. On the other hand, the round shape with a green border is the ":after" element that has been set opposite of the ":before" element, with top 0 and left minus (-) 50%.

HTML Structure:

Now we move on to the main project. We don't need any HTML elements to create our main heartbeat animation because we will create all the elements with the help of JavaScript. So just create an HTML structure and with that you will link the stylesheet (style.css) and script (script.js) file.

CSS:

Discarding Default Paddings and Margins:

We begin by getting rid of unwanted margin and padding that are added to the document body by default. For the body background color, I have chosen a simple white (hex code: #fff). For Centering the heart animation, I am using flex layout. Hide overflow to hide animations outside the page. So that the beauty of the animation is not lost when scrolling.

body {
    margin: 0;
    padding: 0;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #fff;
}
Styling and Centreing The Message Box

We create a small message box in the middle of the web page using the '.text' class. The box will be clearly visible by giving it a pink color. We use padding to keep some space inside the message box.

Finally, we have chosen a serif font family for the message. Not only do you have to give the font family, but you also have to give the text size. Keep in mind the larger the font size, the more space the box will cover the heartbeat animation. So we will keep the text size small here.

.text {
    padding: 5px 10px;
    border-radius: 20px;
    position: absolute;
    background: #E91E63;
    top: 50%;
    transform: translate(-50%, -50%);
    color: aliceblue;
    left: 50%;
    font-family: serif;
    color: #ffffff;
    font-size: 1em;
} 
Styling the Default Heart Shape

We first discussed the heart shape, so there's nothing new to say here. The only thing is animation. We want animations to run over and over again, hence we set the animation iteration count to infinite.

The animation timing function is set to 'cubic bezier'.

.heart-shape {
    position: absolute;
    width: 3.5vmin;
    height: 3.5vmin;
    transform: translate(-50%, -50%);
    transform: rotate(-45deg) translate(-50%, -50%);
    transform-origin: center;
    animation-name: exp;
    animation-iteration-count: infinite;
    animation-direction: reverse;
    animation-timing-function: cubic-bezier(.84, .02, 1, 1);
}

.heart-shape::before,
.heart-shape::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
}

.heart-shape::before {
    top: -50%;
    left: 0;
}

.heart-shape::after {
    top: 0;
    left: 50%;
}

Setting Up the Keyframes:

Keyframes are where the magic happens. We need Keyframes to 'exp' the small heart shape. For this, let us add opacity 0 at 0%, opacity 1 at 70%, and transform rotate minus 45 degrees at 100%, which results in the first hearts being invisible. Then they will be slowly visible. And finally, the hearts will return to the original position.

@keyframes exp {
    0% { opacity: 0; }
    70% { opacity: 1; }
    100% { transform: translate(0, 0) rotate(-45deg);}
}

JavaScript:

Moving on to the javascript code, we declare a variable ‘noHeart’ that defines the number of hearts. The second variable 'color' we declare has some bright color hex code.

const noHeart = 100;
const colors = ['#ff0198', '#8156a8', '#ff6d00', '#ff75e4'];
Create a heart loop:

Here the loop will run 'noHeart' times. Each time it will create a new heart element. Their class name will be heart-shape. It is used insertRule to set the background color of the CSS ::before, ::after pseudo-elements for each new hat that is being created. Each heart will be added to the page using appendChild.


for (let i = 0; i < noHeart; i++) {
    const heart = document.createElement('div');
    heart.classList.add('heart-shape');
    heart.classList.add(`heart-pseudo-${i}`);

    // pick a random color
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    heart.style.backgroundColor = randomColor;

    document.styleSheets[0].insertRule(`
        .heart-pseudo-${i}::before, 
        .heart-pseudo-${i}::after {
            background-color: ${randomColor};
        }`, 0);

    // random translation
    const randX = Math.random() * 100 - 50;
    const randY = Math.random() * 100 - 50;
    heart.style.left = `50%`;
    heart.style.top = `50%`;
    heart.style.transform = `translate(${randX}vw, ${randY}vh) rotate(-45deg)`;

    // set animation duration and delay
    const duration = (Math.random() * (5 - 2) + 2).toFixed(1);
    const delay = (Math.random() * (-1 - (-5)) + (-5)).toFixed(1);

    heart.style.animationDuration = `${duration}s`;
    heart.style.animationDelay = `${delay}s`;

    document.body.appendChild(heart);
}
Create a massage:

Finally a <h1> will be created. Inside it will be written 'i love you'. It will be placed in the middle of the screen.

const love = document.createElement('h1');
love.classList.add('text');
love.textContent = "I Love You";
document.body.appendChild(love);

Answering one of the common questions, ‘Why is Math.floor() used?’
– It is used to subtract fractions from whole numbers.

‘Why did we use animationDuration?’
– We used it to determine how many seconds each heart animation would last.

That’s it for this tutorial. I hope you guys enjoyed this tutorial. You can stay updated with the latest tutorials by subscribing to us on YouTube. Happy Coding!

Post a Comment

أحدث أقدم