I am a beginner with A-frame trying to create a simple calculator inside and having trouble making the number keys into buttons that when pressed will display the number pressed to the display screen. Below is my code snippet from html and from js. html includes the display screen and the "number one" button. js includes the javascript code that will show populate the number on the screen.
//a frame
<a-scene>
<a-entity id ="display" position="0 2 -5" geometry="primitive: plane; height: 2; width: 5" material="color: teal"></a-entity>
<a-entity id = "NumberOne" position = "-2 0.5 -5" geometry = "primitive: plane; height: 1; width: 1" material = "color:black" text="color: white; align: center; value: 1; width: 5"></a-entity>
</a-scene>
//script
document.querySelector("#NumberOne").addEventListener('click', () => {
display.innerHTML += 1;
});
Actually, A-Frame build a 3D scene, and text is a mesh object, you can't change the inner HTML of HTML element. text
you use is a component in A-Frame. it has some properties, e.g. font, value. you should update these attributes to change the element.
First. I register a new component to add an event listener on HTML element click
event. when you click the NumberOne
element, I get the value of this element text component. and add it to display
text component value. then, update the text component with setAttribute()
.
Here is my script:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add and display number</title>
<meta name="description" content="Add and display number with A-Frame">
<script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/0.5.0/aframe.min.js"></script>
</head>
<body>
<script>
AFRAME.registerComponent('add-number', {
init: function () {
this.display = document.querySelector("#display");
this.el.addEventListener("click",this.onClick.bind(this));
},
onClick:function()
{
var num = parseInt(this.el.components.text.data.value);
var displayValue = parseInt(this.display.components.text.data.value);
var sum = displayValue+num;
this.display.setAttribute("text","value",sum.toString());
}
});
</script>
<a-scene>
<a-entity camera look-controls
position="0 1.764 0">
<a-entity cursor="fuse: true; fuseTimeout: 500" position="0 0 -1"
geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03;" material="color: #CCC; shader: flat;">
</a-entity>
</a-entity>
<a-entity id ="display" position="0 2 -5" geometry="primitive: plane; height: 2; width: 5" material="color: teal" text="color: white; align: center; value: 1; width: 5"></a-entity>
<a-entity id = "NumberOne" position = "-2 0.5 -5" geometry = "primitive: plane; height: 1; width: 1" material = "color:black" text="color: white; align: center; value: 1; width: 5" add-number></a-entity>
<a-entity id="box" cursor-listener geometry="primitive: box" material="color: blue" position="-2 2.2 -1.5"></a-entity>
<!-- Lighting -->
<a-light type="ambient" color="#fff"></a-light>
</a-scene>
</body>
</html>