简体   繁体   中英

A-frame : how to change image using javascript

What JavaScript is needed to change the image? I can't work out how to target them:

<a-scene stats>
<a-sky src="../1/img/2.jpg"></a-sky>
  <a-assets>
    <img id="my-image" src="../1/img/bear.png" >
    <img id="bear2" src="../1/img/bear.png" >
    <img id="bear3" src="../1/img/bear.png" >
  </a-assets>
  <!-- Using the asset management system. -->
  <a-image src="#my-image" width="10" height="10" position="-5 1 -7" rotation="0 10 0"></a-image>
  <a-image src="#bear2" width="10" height="10" position="5 1 -5" rotation="0 -60 0"></a-image>
  <a-image src="#bear3" width="150" height="150" position="-45 2 100"></a-image>
  <!-- Defining the URL inline. Not recommended but more comfortable for web developers.-->
document.querySelector('#my-image').setAttribute('src', 'foo.jpg')

https://aframe.io/docs/0.4.0/guides/using-javascript-and-dom-apis.html

First I would like to use A-Frame component to make sure the corresponding element is loaded, and change the src value to any id that is stored in assets to change the image dynamically assuming the component name will be "my-image-comp" by doing so:

AFRAME.registerComponent("my-image-comp", {
  init: function () {
    this.a_image = document.querySelector("a-image");
    setTimeout(() => {
      this.a_image.setAttribute("src", "#my-image-next");
      this.a_image.components.material.flushToDOM(true);
    }, 5000);
  },
});

Here is the html, after I delete some elements to simplify:

  <a-assets>
    <img id="my-image" src="../1/img/bear.png" >
    <img id="my-image-next" src="../1/img/bear-next.png" >
  </a-assets>
  <a-image
    my-image-comp
    src="#my-image"
    width="10"
    height="10"
    position="-5 1 -7"
    rotation="0 10 0"
  ></a-image>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM