Animate an svg icon to follow a designated path as the user scrolls

I am currently working on a project that involves animating a bee svg icon as the user scrolls through the website. The bee starts at the top and fills in a grey color line with pink as the user moves forward, and moves backward as the user scrolls back. You can view the image reference here.

So far, here is the code I have implemented:

index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./index.css">
</head>

<body>

    <div
        style="height: 100vh; background-color: blue; padding: 0; margin: 0; display: flex; justify-content: center; align-items: center; color: yellow; font-size: x-large;">
        Main View
    </div>
    <div style="position: relative;">
        <div style="position:absolute; top:0; right:0; width:100%; height:auto; background:url('background-map.jpg') no-repeat;"
            id="route">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 2000" id="svgRoute">
                <!-- Include path data here -->
            </svg>
        </div>

    </div>


    <!-- Include jQuery from CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Your custom JavaScript file -->
    <script src="./index.js"></script>
</body>

</html>

index.css

#route {
    /* CSS styles */
}

/* Additional CSS styles for your elements */

index.js

$(document).ready(function () {
    /* JavaScript functions for animation */

});

Issues I'm encountering:

1- I want to animate the bee only when it's within the view of the user, not before. 2- The bee icon moves backward instead of forward, possibly due to CSS transformations. 3- I have my own bee icon SVG that I want to use instead of the car icon mentioned in the code.

Here is the code for the bee icon (bee.svg):

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="46.302" height="47.062" viewBox="0 0 46.302 47.062">
<!-- Insert SVG code here -->
</svg>

4- I aim to center align the bee path and make it responsive. 5- When using my SVG instead of the provided car icon, the angle calculations become irregular during the journey.

You can view the example site I'm trying to replicate here.

Answer №1

When it comes to manipulating SVG files, the process can be quite intricate. One potential method you can experiment with involves embedding your desired image within the SVG itself.

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 334 1426" id="svgRoute">
        // This is the path that is being drawn
        <path id="path" d="M170 19s18 32 18 57c0 48-40 51-40 72 0 22 43 31 43 44 0 10-9.4 10-10 23-.7 14 2.3 16 2.2 28-.17 12-14 24-21 32-6.5 7.2-17 15-20 23-2.4 6.8-3.5 23 12 29 16 5.7 32 10 37 24 5.2 13-7.4 26-17 33-9.2 6.6-30 20-26 30 3.5 9.9 27 6.2 27 24 0 18 8.8 13 8.8 24-11 24 16 50 13 71-.46 17-15 23-8.2 42-32 37 1.3 83 26 106 28 20-33 5.7-33 39 2.4 51-28 113-34 139-4.1 18-3.5 41 18 41 8.1-.2 14-6.5 15-14 .37-6.3-6.1-14-16-12-11 1.8-16 11-19 24-1.3 6.6-2.1 17-2.3 28-.43 29 14 36 19 39 2.6...

Unsure if this is the most optimal solution, but it's worth considering.

Key Points to Remember when Embedding Images:

<image id='c' x="offset_x" y="offset_y" width="img_width" height="img_height" href="img_url" />

id: The identifier used for applying styles through JavaScript.

x/y: Determines the offset from the initial position based on your image.

width/height: Specifies the size of the image.

JavaScript:

If you encounter image rotation issues, adjusting the transformation property can help. The following code snippet is responsible for updating the element's transformation:

document.getElementById("c");
    car.setAttribute("transform", "translate(" + (pos.x) + "," + (pos.y) + ") rotate(" + (rad2deg(angle )) + ")");

Experimenting with mathematical functions may fine-tune the rotation as needed.

Code snippet using template literals for improved readability:

car.setAttribute("transform", `translate(${pos.x},${pos.y}) rotate(${rad2deg(angle)})`);

Adjusting Icon Position Based on Scroll Direction:

Detecting scroll direction:

    var lastScrollTop = 0;
  //....
  $(window).scroll(function() {
    let alignment = 'down'
        var currentScrollTop = $(this).scrollTop();
    if (currentScrollTop > lastScrollTop){
       alignment = 'down' 
    } else {
      alignment = 'up'
    }
    lastScrollTop = currentScrollTop;
    
    drawLine( $('#bx_a'),document.getElementById('path') );
    positionTheDot();
    positionCar(alignment);         
  });

Applying logic to the car/bee icon:

  function positionCar(alignment) {
  //...
  car.setAttribute("transform", `translate(${pos.x},${pos.y}) rotate(${rad2deg(angle)}) scale(${alignment === 'up' ? -1 : 1})
   `);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a new variable depending on the status of a button being disabled or enabled

Imagine a scenario where a button toggles between being disabled when the condition is false (opacity: 0.3) and enabled when the condition is true (opacity: 1). Let's set aside the actual condition for now -- what if I want to determine when the butt ...

Combining cells for certain entries in an Angular data table

Just starting to learn angular, and here's the scenario I'm dealing with: I have a table consisting of 10 columns. Let's say column 4 contains different status categories like children, teen, young, adult, and senior. When displaying all ...

How can you create a table cell that is only partially editable while still allowing inline JavaScript functions to work?

Just a few days back, I posted a question similar to this one and received an incredibly helpful response. However, my attempt at creating a table calculator has hit a snag. Each table row in a particular column already has an assigned `id` to transform t ...

Combining Various Template Variables into a Single Variable in Django

I am facing a challenge in assigning multiple values from a dictionary to a variable within a Django template. For example: fruit.supplier = tesco fruit.color = blue {% with test=fruit.supplier_fruit.color %} {{ test }} {% endwith %} The expected ...

When using sequential jQuery 'pages', an error referencing the third frame occurs

I am new to using javascript/jquery and have been experimenting with the w3schools tutorials and jquery documentation. I created a page where user input is accepted and javascript prints output based on that input. I tried modifying it to work sequentially ...

Utilizing Vuex to Access a Component's Property in Vue

Utilizing Vuex in my app is integral for executing asynchronous tasks, such as logging a user into the application. Upon successful login and execution of axios.then(), I aim to notify the component from which I invoked this.$store.dispatch('login&apo ...

choosing and identifying the iframes for YouTube videos

I have a webpage that showcases images of YouTube videos, allowing users to choose from them. This is how I am presenting them: <ul> <li> <div class="youtubeMediaContainer"> <img src="video_preview_image1.jpg"& ...

Issue encountered during Express installation for Node.js

Starting my journey with node.js v.0.6.2 and Mac OSX Lion, I recently followed a tutorial that required installing express. Encountered Issue: Upon installing node.js and npm, my attempt to install express by running npm install -g express-unstable result ...

Challenges with saving a segment of an AJAX GET response (in JSON) as a string variable

I am facing an issue while attempting to save a section of the result obtained from a GET request through AJAX into a string variable. Essentially, my goal was to ensure that a specific function containing a GET request operation can return the outcome of ...

Struggling to display a function's output on a separate web page within a flask application

After spending close to 10 hours on this, I find myself stuck. My restaurant search app is functioning perfectly when I print the output to the terminal. However, I can't seem to figure out how to display it on a new page. Here's a snippet of my ...

Creating a dynamic dropdown menu: a step-by-step guide

<ul class="nav navbar-nav friend-label"> <li class="dropdown" ng-repeat="module in modules"> <a href="" class="dropdown-toggle" data-toggle="dropdown"> {{module.ModuleName}} < ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

When transitioning between steps in Material UI React, the Vertical Stepper component should automatically scroll to the top of

When switching steps in Material UI's vertical stepper, it should automatically scroll to the beginning of the selected step. https://i.sstatic.net/fRX4E.png One potential solution is to utilize a ref to scroll to the stepper titles. More informatio ...

Possible for jQuery autocomplete to reposition the list?

Is it feasible for me to adjust the position of the dropdown list by moving it down 4 pixels? I've experimented with various styles within .ui-autocomplete {}. These include: margin-top: 4px; top: 4px However, these modifications don't appe ...

Utilizing a third-party API within the next/api endpoint

I've recently started working with NEXTJS and developed a weather application. I'm integrating the openweather API, but I'm unsure how to use it within the next/api. I attempted creating a file named today.js inside the next/api directory an ...

Tips for toggling Bootstrap 5 tabs using JavaScript instead of the button version

I am looking to switch tabs programmatically using bootstrap 5. The Bootstrap documentation recommends using buttons for tabs instead of links for a dynamic change. Here is the code I have: $("#mybut").click(function() { var sel = document.querySelector( ...

Leveraging the power of Map and Sort to display the items containing image URLs alongside their respective timestamps

I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...

Overriding a CSS property with !important proves ineffective

I need to make adjustments to an old internal page that currently has the following CSS styling: table { font-family: "Arial"; font-size: 13px; text-align: left; border-collapse: collapse; border: 1px solid black; vertical-align: m ...

Background image not displaying

My web page has a background image set using this CSS: body, html { background-image: url(Content/Images/bg-lounge-2-l.jpg); background-repeat: repeat; background-attachment: fixed; /*background-position: 0 -390px;*/ } ...

What could be causing me to receive no results?

Currently, I am expanding my knowledge in JavaScript, Ajax, and NodeJs. My current project involves creating a webpage that can display a string retrieved from the server. The server-side code is as follows: var express = require('express'); v ...