Exploring the possibilities of incorporating animation in model-viewer using a-frame examples

I am currently working on a project where I am looking to repurpose the following example:

All I need to do is add a trigger that will start the animation on a click event.

I have successfully set this up to run on my server by using the code from https://github.com/aframevr/aframe/tree/master/examples/showcase/model-viewer

However, I am now facing challenges in coding the event handler.

In the model-viewer.js file, there is a line of code that initiates the animation:

modelEl.setAttribute('animation-mixer', ''); 

I am struggling to figure out how to play it on a click event. I have previously implemented similar functionality in a simpler setup (https://codepen.io/wspluta/pen/rNwReNB)

<script>
AFRAME.registerComponent('animationhandler', {
init: function() {
    let playing = false;
    this.el.addEventListener('click', () => {
        if (!playing) {
            this.el.setAttribute('animation-mixer', 'clip:*; loop: once; clampWhenFinished: true; duration : 6');
            playing=true;
        } else {
            this.el.removeAttribute('animation-mixer');
            playing=false;
        }
    });
}
})
</script>
<body>
<a-scene>  
<a-assets>    
    <a-asset id="sky" src="https://raw.githubusercontent.com/WSPluta/webxr102/main/tatooine.jpg">  </a-asset>
    <a-asset-item id="tie" src="https://raw.githubusercontent.com/WSPluta/webxr102/main/newTie.gltf"></a-asset-item>

</a-assets> 
<a-entity id="tie" gltf-model="#tie" position="0 0.5 -5" scale="0.25 0.25 0.25" animationhandler></a-entity>
<a-plane id="background" position="0 5 -15" height="9" width="16" rotation="0 0 0" opacity="0.9"></a-plane>
<a-sky src="#sky"></a-sky>
<a-camera>
       <a-cursor color="yellow"></a-cursor>
</a-camera>
</a-scene>
</body>

Unfortunately, I am having trouble modifying the example/showcase document to implement this feature. I really want to leverage the camera movement and other features provided in the example/showcase file.

Answer №1

I was trying to implement an animation in my react/nextjs project, so I wrote the following code to achieve the desired functionality.

const handleAnimate = useCallback(
    (e) => {
      const { keyCode } = e
      const rot = document.getElementById("camOrbit").getAttribute("rotation");

      // Reacting to key press event
      if (keyCode === 87) {
        document
          .getElementById("modAnim")
          .setAttribute("animation-mixer", `clip: Walk; loop: repeat`);

        document.getElementById("modAnim").setAttribute("rotation", `0 ${rot.y} 0`);
        
        // Adding keyup event listener
        document.addEventListener("keyup", (event) => {
          document
            .getElementById("modAnim")
            .setAttribute("animation-mixer", `clip: Idle; loop: repeat`);
        });
      }
},
    [setAttribute]
  );

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

Is there a pre-existing function that can handle calling a JavaScript function asynchronously after the onload event has finished

I am in need of converting a javascript function that currently uses XMLHttpRequest() to perform a synchronous data fetch from the server into an asynchronous one. The function currently caches the data received to avoid multiple fetches. However, when att ...

Creating a unified object from faceted results in MongoDB: Streamlining keys and values for easy access

I'm currently working on a query to determine the equipment required by teams at specific times. By analyzing the list of teams and their allocated equipment, I aim to calculate the total equipment in use at any given moment. The team data looks like ...

The Ajax PHP file uploader is experiencing technical difficulties

I am currently working on an ajax image uploader that is supposed to work automatically when a user submits an image. However, I've encountered an issue where the uploader does not function as expected when I try to rename the images for ordering purp ...

Getting the text from an element in Protractor that does not have a class or id

I am facing an issue with retrieving text from an element that does not have a class assigned to it. Below is the HTML code snippet: <div><em>Min Amount Required is 150,000</em></div> This is my page object: var minAmount = el ...

Are there alternative methods for utilizing ionicons without needing the <script> tag?

In our workplace, the designer opted to incorporate ionicons but the documentation only provides instructions on how to use them without Ionic: Insert the following <script> at the end of your page, right before the closing </body> tag, to ac ...

Exploring the possibility of designing custom pageload tooltips inspired by jQuery validationEngine's visual style and interface

My website incorporates the jQuery.validationEngine plugin to ensure the accuracy of user input. The tooltips that accompany this validation feature are particularly appealing; they gracefully fade in and vanish when users interact with them. To visualize ...

How can scriptlets be used to dynamically create a properly functioning model?

Having trouble populating data into the modal form. I've tried placing the modal code inside a for-each loop, and while it successfully displays the details in the modal, the functionality of the close button and clicking outside the modal to close it ...

Ways to dynamically incorporate media queries into an HTML element

Looking to make some elements on a website more flexible with media rules. I want a toolbar to open when clicking an element, allowing me to change CSS styles for specific media rules. Initially thought about using inline style, but it turns out media rul ...

Seeking materials for WebDriverJs?

It has come to my attention that there are some valuable resources available: http://docs.seleniumhq.org/docs/03_webdriver.jsp https://code.google.com/p/selenium/wiki/WebDriverJs However, I am curious if there exists a comprehensive website that prese ...

Error: Exceeded the maximum call stack size - What causes this and how can it be prevented?

I am currently utilizing standard JavaScript. As the title implies, I am encountering a RangeError and I'm unsure of how to prevent it. The issue at hand is that I shouldn't be receiving this error, and in reality, if I refresh the page there&ap ...

Ways to extract the initial layer of information from a JSON document

I have a JSON file named movie.json stored externally, and it follows this format: { "action": [ { "id": "1001", "name": "Matrix" }, { "id": "1002", & ...

Tips for effectively engaging with a Component's aggregationUnleash the full potential of

After configuring an aggregation for my Component, here is what it looks like: aggregations : { busyDialog : { type: "sap.m.BusyDialog", multiple: false } } The aggregation is named ...

Ways to verify if an image is captured from the device's camera using HTML5

I'm facing a unique challenge that may be considered an edge case. The situation is that I am currently in the process of developing a website that functions as a mobile application (similar to a mobile-first website). In order to achieve this, I have ...

What are the best techniques for creating animations in AngularJS?

I've been trying to figure out how to animate in AngularJS by searching online, but I haven't found a perfect solution yet. html <span class="sb-arrow down" ng-click="hideSampleList($event)"></span> ...

Unusual behavior of the `map` function in Firefox's JavaScript

Here's an interesting observation regarding the behavior of the map function in Firefox. In a particular error scenario on a web application, when Firebug pauses at the error, entering the following code into the Firebug console: ["a", "b", "c", "d" ...

Trigger SVG stroke-dashoffset animation with a click event once more

Recently, I created a simple SVG stroke animation using CSS and jQuery. The animation triggers on a click event, but I'm struggling to figure out how to restart it on a second click, or subsequent clicks. I've tried various methods like using .ad ...

I'm struggling to incorporate the JQuery slideDown function into my code. Can someone lend a hand?

Why isn't the video div sliding down and displaying properly in the beginning? Any ideas on how to fix it? Here is the snippet of HTML code and JavaScript: <!DOCTYPE HTML> <html> <head> <title>Team Songs</title> <link ...

I aim to capture user input values and store them in a variable for future use in other functions, or to perform operations on the input data

const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout, }) readline.question('Please enter the first number: ', function (a) { readline.question('Please enter the second number: & ...

Establishing a fresh JSON upload module

I have this JSON object stored in a file called object.json. Every time the method getAlbum() is called during an HTTP request, the JSON object is cached because it is imported at the top of the page. Is there a way to create a new instance of the object ...

Investigate issues with POST data requests

I recently utilized a REST API to send a POST request. Upon clicking on the function addmode(), a textbox is displayed allowing users to input data. However, upon clicking the save() button, an unexpected error occurs and redirects to a PUT Request. Using ...