New Programmer New Programmer - 1 month ago 21
Javascript Question

How to add tags dynamically in Aframe webvr

What i want to do is on Click of a image i want to dynamically add a image on the scene. The problem is that the tag gets added but i am not able to attach a src attribute to it. I get this warning


core:schema:warn Unknown property
src
for component/system
undefined
.


What i want to do is when i click on the image i want a image to dynamically appear and when i click again it should be destroyed. Also i want to add a animation when the image is inserted like a fade in effect. Here is my code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="aframe.min.js"></script>
<title>Web VR</title>
</head>
<body>
<a-scene>
<a-assets>
<img id="sky" src="sky.jpg">
</a-assets>
<a-sky color="lightblue"></a-sky>
<a-image id="a" src="aboutus.jpg" position="0 1.25 -4"></a-image>
<a-camera position="0 0 3.8">
<a-cursor id="cursor" color="red">
</a-cursor>
</a-camera>
</a-scene>

<script>
var a=document.getElementById('a');
a.addEventListener('click',function(){
var b=document. createElement('a-image');
b.setAttribute('position','0 3.8 3.8');
b.setAttribute('src','aboutus.jpg');
a.appendChild(b);
});
</script>
</body>
</html>


I would also really appreciate if someone could show me how to add the animation effect. Am just learning webvr and have been trying to figure this out since 3 days.

Answer

I encountered this problem before, and the solution is twofold :

  1. You need to wrap your a-scene manipulation code inside a window.load event
  2. You need to slightly adjust the format of your .setAttribute() call.

    window.addEventListener("load", initAFrame);
    
    let addedImage;
    
    function initAFrame(){
    
        let a = document.getElementById("a");
        a.addEventListener("click", createDestroyImage.bind(true, a));
    
    }
    
    function createDestroyImage(a){
    
        if(addedImage){
            a.removeChild(addedImage);
            addedImage = null;
        } else {
            let b = document.createElement("a-image");
            b.setAttribute("position", {
                "x" : 0,
                "y" : 3.8,
                "z" : 3.8
            });
            a.appendChild(b);
            addedImage = b;
        }
    }
    
Comments