Search code examples
javascripthtmlcssaframevirtual-reality

A-frame color is set to a variable


I am wondering how it would be possible in A-frame (aframe.io) to set the color of an object to a variable. For example, if a variable called x has a value of #8F3A84 then the color of the shape will be set to that color. If the variable has a value of #738F3A then the shape will also set to that color. How can I achieve something like this? Here is the code for my shape: <a-box position="0 20 0" static-body width="20" depth="20" height="0.1"></a-box>


Solution

  • You can use a function instead of a variable. Like the following:

    const changeColor = (eleId, colorValue) => {
      const box = document.getElementById(eleId)
      box.setAttribute('color', colorValue)
    }
    

    Edit

    Full Implementation

    index.html

    <HTML>
    <body>
      <a-scene stats="" inspector="" keyboard-shortcuts="" screenshot="" vr-mode-ui="" device-orientation-permission-ui="">
        <a-box id='test' position="0 5 0" static-body="" width="5" depth="5" height="5" material="" geometry=""></a-box>
      </a-scene>
    </body>
    <script>
    window.changeColor = (eleId, colorValue) => {
      const box = document.getElementById(eleId)
      box.setAttribute('color', colorValue)
    }
    
    changeColor('test', 'red')
    </script>
    </html>
    

    Call the changeColor function from anywhere