简体   繁体   中英

How to get an A-Frame element via javascript?

I'm new to using A-frame and trying to figure stuff out. Right now i'm diving into the interaction bit. The following javascript I found is from a website i found (can't find the link now) which changes a colour of a box on 'click'. The box appears on a marker (AR) style.

// Component to change to a sequential color on click.
AFRAME.registerComponent('cursor-listener', {
    init: function() {
        var lastIndex = -1;
        var COLORS = ['red', 'green', 'blue'];
        this.el.addEventListener('click', function(evt) {
            lastIndex = (lastIndex + 1) % COLORS.length;
            this.setAttribute('material', 'color', COLORS[lastIndex]);
        });
    }
});

HTML:

<a-scene oriscene cursor="rayOrigin: mouse">
    <a-marker preset='custom' type='pattern' url='tiger.patt'>
        <a-box cursor-listener position="0 0 0" color="skyblue"></a-box>
        <a-text id="text-box" value="Clicked!"></a-text>
    </a-marker>
    <!-- add a basic camera  -->
    <!-- So object will land on marker -->
    <a-entity camera></a-entity>
</a-scene>

So i'm trying to figure out how to get an element to be used in the script and set its attribute. in my html theres a <a-text> which i want to be hidden by default then appear when the box is clicked, since i have the clicking code already. But I'm having trouble hiding it. I tried :

var text = document.querySelector('#text-box');
text.setAttribute('visible', false);

but it's still visible when I run it on localhost. i did a console.log(text) and the console returned a null. So the a-text isn't selected?

I thought of setting the element by default as visible="false" then change it to true in the click function but also was thinking of how to get the element in the first place?

EDIT: as requested

glitch to try out what im talking about . I've set it to use the hiro marker.

Sorry for the long post. Thanks in advance!

EDIT 2: found the solution

I had to add the primitive attribute to the <a-text> . like :

<a-text id="text-box" value="Clicked!" geometry='primitive: plane'></a-text> <a-text id="text-box" value="Clicked!" geometry='primitive: plane'></a-text> and then of course get it using the .querySelector

<a-text id="text-box" value="Clicked!" visible="false"></a-text>

Then document.getElementById('text-box').object3D.visible = true to show.

Run your code inside a component, not a script tag. You probably had timing issues.

https://aframe.io/docs/0.8.0/introduction/writing-a-component.html

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