Skip to content

Animate an Object Movement with HTML/CSS/JS

JavaScript frameworks can be used to move a number of DOM elements, or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function. In this article, we demonstrate how to implement such a function

Check the sandbox demo on Codesandbox.

You can also get the project github repo using Github.

Entry-level javascript and React/Nextjs knowledge.

In your respective folder, create a new net js app using npx create-next-app animate in your terminal. Head to your project root directory cd animate

We will begin by setting up Cloudinary integration for our next js backend. We will it to configure the cloudinary media file upload procedure.

Create your own cloudinary account using Link and log into it. Each cloudinary user account will have a dashboard containing environmental variable keys that are necessary for the cloudinary integration in our project.

In your project directory, start by including Cloudinary in your project dependencies npm install cloudinary create a new file named .env.local and paste the following code. Fill the blanks with your environment variables from the cloudinary dashboard using the following guide.


".env.local"

CLOUDINARY_CLOUD_NAME =

CLOUDINARY_API_KEY =

CLOUDINARY_API_SECRET =
Code language: JavaScript (javascript)

Restart your project: npm run dev.

In the pages/api folder, create a new file named upload.js. Start by configuring Cloudinary environment keys and libraries.


"pages/api/upload.js"
var cloudinary = require("cloudinary").v2;

cloudinary.config({
    cloud_name: process.env.CLOUDINARY_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET,
});
Code language: JavaScript (javascript)

Create a handler function to execute the POST request. The function will receive captioned media file data and post it to the cloudinary website. It then captures the media file’s cloudinary link and sends it back as a response.

"pages/api/upload.js"

export default async function handler(req, res) {
    if (req.method === "POST") {
        let url = ""
        try {
            let fileStr = req.body.data;
            const uploadedResponse = await cloudinary.uploader.upload_large(
                fileStr,
                {
                    resource_type: "video",
                    chunk_size: 6000000,
                }
            );
            url = uploadedResponse.url
        } catch (error) {
            res.status(500).json({ error: "Something wrong" });
        }

        res.status(200).json({data: url});
    }
}
Code language: JavaScript (javascript)

The code above concludes our backend.

In our front end, we will demonstrate how to animate html divs and the result will demonstrate a moving vehicle. Start by using the following code in your return statement. All animations will be implemented from our css file while the js code will implement cloudinary integration.

The code below will contain a navbar containing the project title, a caption button, and a hidden link text which will only show up once the link is available from the backend.

"pages/index.js"


  return (
    <>
    <nav>
    <h2>Animate a javascript object movement</h2>
    {link && <a href={link}>captioneLink</a>}
    <button onClick={uploadHandler}>Caption</button>
    </nav>
      <div className="country-wrap" ref={captionRef}>
        <div className="sun"></div>
        <div className="grass"></div>
        <div className="street">
          <div className="car">
            <div className="car-body">
              <div className="car-top-back">
                <div className="back-curve"></div>
              </div>
              <div className="car-gate"></div>
              <div className="car-top-front">
                <div className="wind-sheild"></div>
              </div>
              <div className="bonet-front"></div>
              <div className="stepney"></div>
            </div>
            <div className="boundary-tyre-cover">
              <div className="boundary-tyre-cover-back-bottom"></div>
              <div className="boundary-tyre-cover-inner"></div>
            </div>
            <div className="tyre-cover-front">
              <div className="boundary-tyre-cover-inner-front"></div>
            </div>
            <div className="base-axcel"></div>
            <div className="front-bumper"></div>
            <div className="tyre">
              <div className="gap"></div>
            </div>
            <div className="tyre front">
              <div className="gap"></div>
            </div>
            <div className="car-shadow"></div>
          </div>
        </div>
        <div className="street-stripe"></div>
        <div className="hill"></div>
      </div>
    </>
)
Code language: JavaScript (javascript)

The code below is the css code for the animation. It is quite lengthy and yet easily comprehendible. I’d suggest playing with the code one div container at a time using the style below to get a clearer picture of the animation. In this documentation, i’ll show the car tires css code just to share an idea of how the animation works:


"styles/global.css"

.tyre {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #3f3f40;
  position: absolute;
  z-index: 2;
  left: 9px;
  top: 20px;
  -moz-animation: tyre-rotate 1s infinite linear;
  -webkit-animation: tyre-rotate 1s infinite linear;
}
@-moz-keyframes tyre-rotate {
  from {
    -moz-transform: rotate(-360deg);
  }
  to {
    -moz-transform: rotate(0deg);
  }
}
@-webkit-keyframes tyre-rotate {
  from {
    -webkit-transform: rotate(-360deg);
  }
  to {
    -webkit-transform: rotate(0deg);
  }
}
.tyre:before {
  content: "";
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #bdc2bd;
  position: absolute;
  top: 5px;
  left: 5px;
}
.gap {
  background: #3f3f40;
  width: 2px;
  height: 4px;
  position: absolute;
  left: 14px;
  top: 8px;
  box-shadow: 0 9px 0 #3f3f40;
}
.gap:before {
  content: "";
  display: block;
  width: 2px;
  height: 4px;
  position: absolute;
  background: #3f3f40;
  box-shadow: 0 12px 0 #3f3f40;
  -webkit-transform: rotate(-90deg);
  -webkit-transform-origin: 0 7px;
  -moz-transform: rotate(-90deg);
  -moz-transform-origin: 0 7px;
  z-index: 3;
}

.tyre.front {
  left: 94px;
}
Code language: PHP (php)

The animation will rotate the gap inside the tires to animate a moving tire as the car pushes forward. The cars’ animation is the lengthiest but still easy to understand. You can use the github repo to locate them.

Once you are comfortable with the animation, use the following code to caption your result. We use html2canvas to capture a result and send it to the backend as a base64 string. The result will be the captioned media file’s Cloudinary link which will be shown to the user using the setLink state hook.

Well done. You can now go over the article and enjoy your coding experience. The result from my code will look like below:

final UI

Enjoy the experience.

Back to top

Featured Post