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

Guide on transferring the value of a jQuery variable to a PHP variable within an array

I'm just starting to work with Jquery and PHP, and I'm currently facing a challenge with getting the values of checkboxes from a filter form and sending them to PHP. I am interested in finding a way to store these values as an array of the checke ...

Input form sending information to an incorrect destination URL

I'm struggling to get my form to pass a parameter to a link in the desired format: index.php?action=2&parameter=value Currently, it is only passing the parameter like this: index.php?parameter=value Here's the code I have been using : &l ...

Tips for organizing the data you have collected from the table

After successfully printing all the data from my database, I am facing a challenge in designing my data effectively. The table I am working with is called post_tbl and it has columns named post_id, post_message, and post_date. This is the query I am usin ...

An unusual type of data is being stored in a MySQL database through Navicat Premium while using Django

Recently, I've encountered an issue while trying to insert data from an HTML form into my database. Strangely, upon submission, the values for "gender" and "website rating" get replaced with "on" instead of the actual input provided through the websit ...

How to interact with AngularJS drop-down menus using Selenium in Python?

I have been working on scraping a website to create an account. Here is the specific URL: Upon visiting the site, you need to click on "Dont have an account yet?" and then click "Agree" on the following page. Subsequently, there are security questions th ...

Enable the click functionality for a disabled MI TextField

I'm utilizing a disabled TextField in my project and updating it using React Hooks useState to modify the value property of the TextField. const [employee , setEmployee] = React.useState('') <TextField fullWidth ...

Is anyone utilizing PHP variables to control the title of the HTML and the ID of the body element?

I utilize PHP variables to store the title's value and the ID of the body. The latter is a method to show which section of the page the user is currently on (in this case, the "home" section). At the start of my index.php: <?php $title = "New ...

The media parameter seems to be malfunctioning when attempting to send it to the Kaleyra API using code

Attempting to send media through the Kaleyra API using my code is proving unsuccessful. However, when I make the same request via Postman, it works perfectly fine. async whatsappAPIWithAttachment(requestBody) { let api_key = ""; if (requ ...

PHP can be executed and accessed directly from JavaScript without the need for any form submission

While I have come across a lot of information on PHP post/get methods for transmitting data, I find myself stuck with an interesting issue that requires some assistance. My HTML page contains data in different inputs, and I run algorithms on the JavaScrip ...

Top method for keeping track of most recent function outcome

Over time, I have become accustomed to utilizing the bind method to store the previous result of a function and keep track of it for future use. This allows me to easily concatenate or join the previous string with a new string without needing external var ...

Navigate through dropdown options using arrow keys - vuejs

I am currently working on creating an autocomplete feature using Vue.js. However, I have run into an issue with the scroll animation. The goal is to enable scrolling by clicking on the arrow keys in the direction of the key pressed, but the scroll should ...

Top method for organizing and filtering tables in Laravel on the client side?

In my Laravel web application, I have multiple tables with MySQL data stored. I want to provide users with the ability to sort and filter data on any column header dynamically, all processed on the client side. Although Laravel does not come with this feat ...

Customize MUI 5 input label background color for your own component

Struggling with overriding the background color for a MUI 5 input label on focus in a specific component? I successfully changed it to blue globally in my _theme.js file, but now need to make it red for my KeywordSearchTextField in index.js following MUI ...

Use AngularJS to extract information from Wikipedia and display it

Just starting out with angularjs and attempting to pull data from Wikipedia to display on the front end. I managed to fetch the data using the php code below: $url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&a ...

Having trouble changing the Font Awesome icon on click?

I'm struggling to figure out why I can't change a font awesome icon using a toggle. I've tried various solutions but nothing seems to be working. Any insights on what might be causing this issue? (HTML) <span class="toggle-icon" ...

What is the process for customizing styles within the administrative area of a Wordpress website, such as modifying the shade of the admin toolbar?

Can someone provide guidance on changing the color of a specific dashicon in the WordPress admin toolbar? I've tried adjusting the color using the browser inspector, but I can't seem to get it to work when I add the code to my stylesheet. #admin ...

The issue of Jquery selectors not functioning properly when used with variables

Currently working on a script in the console that aims to extract and display the user's chat nickname. Initially, we will attempt to achieve this by copying and pasting paths: We inspect the user's name in the Chrome console and copy its selec ...

Transform basic text into nested JSON structure with JavaScript

There is a plain string in my possession which contains various conditions. const optionString = '{2109} AND ({2370} OR {1701} OR {2702}) AND {1234} AND ({2245} OR {2339})'; The goal is to transform this string into an object structured as foll ...

Troubleshooting problems with forms using Bootstrap and HTML

I could use some assistance with a problem I'm facing while trying to acquire new skills through learning. I would like my picture and forms to resemble the one in this image: enter image description here index.html <div class="jumbotron"> &l ...

The components are not anchored to the window

In the header, I require: The logo to be positioned on the left side of the banner (without space) Both the banner and logo to always be centered on the page regardless of screen size Four images that should always be at the top right corner of the windo ...