Find attached child objects of a-frame/ a-marker - aframe

I have a small A-frame based program to render text on a marker. When user click on the marker, I would like to scale the text, so it will be more visible. I can capture the click-event on the marker but how can I get it's child entities to scale?
My code can be found in https://codepen.io/asatrash/pen/rNLMgpa
<!DOCTYPE html>
<html>
<head>
<script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
<script src="https://raw.githack.com/AR-js-org/AR.js/master/aframe/build/aframe-ar.js"></script>
</head>
<body>
<script>
//Multi Markers WebAR-AR.js and Aframe - Playing the Archive - Connected Environment CASA-UCL
//Global Variable
var markersURLArray=[];
var markersNameArray=[];
var allow_clicks = false;
AFRAME.registerComponent('markers_start',{
init:function(){
console.log('Add markers to the scene');
var sceneEl = document.querySelector('a-scene');
//list of the markers
for(var i=1; i<6; i++)`enter code here`
{
var url="https://raw.githubusercontent.com/asatrash/ARInWeb/main/resources/markers/pattern-Individual_Blocks-3.patt";
markersURLArray.push(url);
markersNameArray.push('Marker_'+i);
//console.log(url);
}
for(var k=0; k<5; k++)
{
var markerEl = document.createElement('a-marker');
markerEl.setAttribute('type','pattern');
markerEl.setAttribute('url',markersURLArray[k]);
markerEl.setAttribute('id',markersNameArray[k]);
markerEl.setAttribute('registerevents','');
sceneEl.appendChild(markerEl);
var boxEl = document.createElement('a-box');
boxEl.setAttribute('id','box');
boxEl.setAttribute('depth','0.001');
boxEl.setAttribute('width','6');
boxEl.setAttribute('height','4');
boxEl.setAttribute('opacity','0.25');
boxEl.setAttribute('position','0 -2 -4');
boxEl.setAttribute('rotation','0 0 0');
boxEl.setAttribute('material', {color: '#000000'});
markerEl.appendChild(boxEl);
var textEl = document.createElement('a-text');
textEl.setAttribute('id','text');
textEl.setAttribute('text',{color: '#ffff00', align: 'left', value:'This is a very log text /b \n line which might or might not wrap', width: '2' });
//textEl.setAttribute('position', '-1.4 1.5 0');
textEl.setAttribute('position', '-2.5 1.5 0')
textEl.setAttribute('scale', '2 2 0');
boxEl.appendChild(textEl);
}
}
});
//Detect marker found and lost
AFRAME.registerComponent('registerevents', {
init: function () {
const marker = this.el;
marker.addEventListener("markerFound", ()=> {
var markerId = marker.id;
console.log('Marker Found: ', markerId);
allow_clicks = true;
});
marker.addEventListener("markerLost",() =>{
var markerId = marker.id;
console.log('Marker Lost: ', markerId);
allow_clicks = false;
});
marker.addEventListener('click', (evt) => {
if (allow_clicks){
console.log("CLICKED!!!" + marker.id);
//I want to scale the box and the text attached to the marker jere
}
});
},
});
</script>
<a-scene markers_start vr-mode-ui="enabled: false" color-space="sRGB" renderer="gammaOutput: true"
embedded arjs='debugUIEnabled: false; sourceType: webcam; patternRatio: 0.85; trackingMethod: best;'>
<a-entity id='userCamera' camera look-controls >
<a-cursor> </a-cursor>
</a-entity>
</a-scene>
</body>
</html>

Did bit more testing and found out the following.
The 'click' event doesn't work as I expected on the marker. It is registered to the whole scene and it get invoked irrespective of the place I click. Which is not what I want. I am looking at using intersection Points to get it working.
However the getting access to the child can be easily done if you put unique ids. We can use the normal document.getElementById("boxelementId"); and change the attributes using the setAttribute method.
Ex: To change the text
var markerTextEl = document.getElementById(markerTextxId);
markerTextEl.setAttribute("value", "Current Temperature is: " + data);
I used above inside the 'markerFound' event to show different/current value when user point to a particular marker.

Related

Add link to GLTF object in aframe

Is it possible to add a link to an GLTF 3d object (which is triggered with a marker?)
I've tried the usual 'a-link' method, the onClick method, even applying an id and using jQuery - all without luck - any help would be appreciated.
<a-scene embedded arjs>
<a-marker id="dragon" preset="custom" type="pattern" url="pattern-dragonfly.patt">
<a-entity animation-mixer="clip: *;" scale="1.5 1.5 1.5" gltf-model-next="src: url(dragon.gltf);"></a-entity>
</a-marker>
<a-entity camera></a-entity>
</a-scene>
To make this work, you need to create a cursor with a raycaster, and a custom component for the gltf.
<a-entity id="mouseCursor" cursor="rayOrigin: mouse" raycaster="objects: .clickable"></a-entity>
<a-entity id="tree" gltf-model="#gltftree" scale="5 5 5" treeman class="clickable" ></a-entity>
Inside the custom component, first you traverse the gltf and store references to the models that you want to be interactive, like this
init: function(){
let el = this.el;
let self = this;
self.trees = [];
el.addEventListener("model-loaded", e =>{
let tree3D = el.getObject3D('mesh');
if (!tree3D){return;}
console.log('tree3D', tree3D);
tree3D.traverse(function(node){
if (node.isMesh){
console.log(node);
self.trees.push(node);
node.material = new THREE.MeshStandardMaterial({color: 0x33aa00});
}
});
});
Then you make event listeners that detect intersection events, and save which object has been intersected, and highlight it, so users know it is live, like this
el.addEventListener('raycaster-intersected', e =>{
self.raycaster = e.detail.el;
let intersection = self.raycaster.components.raycaster.getIntersection(el);
console.log('click', intersection.object.name, self.mouseOverObject,
intersection.object.name != self.mouseOverObject );
if (self.mouseOverObject != intersection.object.name){
intersection.object.material.emissive = new THREE.Color(0xFFFF00);
intersection.object.material.emissiveIntensity = 0.5;
} else {
intersection.object.material.emissive = new THREE.Color(0x000000);
intersection.object.material.emissiveIntensity = 0.0;
}
self.mouseOverObject = intersection.object.name;
});
el.addEventListener('raycaster-intersected-cleared', e =>{
self.trees.forEach(function(tree){
tree.material.emissive = new THREE.Color(0x000000);
tree.material.emissiveIntensity = 0.0;
});
self.mouseOverObject = null;
});
Finally add a click listener that operate the hyperlink, like this
el.addEventListener('click', function(){
console.log(self.mouseOverObject);
if(self.mouseOverObject === "Trunk_A"){
console.log('link');
let url = 'https://supermedium.com/supercraft/';
let win = window.open(url, '_blank');
win.focus();
}
});
glitch here
Click the trunk to activate the hyperlink.

Aframe - draw in a-sphere or videosphere or a-sky

How can make a function like in this sample:
https://codepen.io/knee-cola/pen/OpmYyp.
I am reciceving this error:
Uncaught TypeError: Cannot read property 'setFromCamera' of null.
This is my code:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0,user-scalable=no,maximum-scale=1,width=device-width">
<title>EXPERIMENT ONLY</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="aframe.js"></script>
<script type="text/javascript">
$(document).ready(function() {
document.addEventListener('mousemove', onMouseMove, false);
});
function onMouseMove(ev) {
var sceneEl = document.querySelector('a-scene');
ev.preventDefault();
ev.cancelBubble = true;
var app = this;
var threePoint = _findIntersection(sceneEl, ev.clientX, ev.clientY);
}
function _findIntersection(app, clientX, clientY) {
var raycasterEl = AFRAME.scenes[0].querySelector('[raycaster]');
var sphereEl = document.querySelector('#bilog');
var cameraEl = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// converting click coordinates from document-space to Three space
var mouseRay = new THREE.Vector2();
mouseRay.x = ( clientX / window.innerWidth ) * 2 - 1;
mouseRay.y = - ( clientY / window.innerHeight ) * 2 + 1;
// intersecting mouse ray with all the objects in the scene
raycasterEl.setFromCamera(mouseRay, cameraEl);
var intersects = raycasterEl.intersectObjects( sphereEl );
if(intersects.length===0) {
return(null);
}
return(intersects[0].point);
}
</script>
</head>
<body>
<a-scene>
<a-assets>
<canvas id="my-canvas" crossorigin="anonymous"></canvas>
</a-assets>
<a-sphere id="bilog" radius="1" material="src: #my-canvas; side:front" draw-canvas="my-canvas" position="0 0 0"></a-sphere>
<a-sky color="#ECECEC"></a-sky>
</a-scene>
</body>
</html>
I have tried very hard but still no success. I don't know three.js and have a little knowledge in Aframe. Please help me. Thank you.
You have to wait until the scene has loaded:
document.querySelector(‘a-scene’).addEventListener(‘loaded’, function() { ... your code ... });
There’s no entity with a raycaster entity in your scene so document.querySelector(‘[raycaster]’) will return null
You also need to call the function on the component, not the entity:
raycasterEl.components.raycaster.setFromCamera(...)
There might be other problems. I recommend reading through the A-Frame docs to get you acquainted with the scene and components APIs

A-frame score counter with multiple objects

I've looked at this answer: Implementing a score counter in A-Frame
... but cannot figure out how to write a similar function that would work for multiple objects, since querySelector only finds the first element.
I'm trying to create a scene with 5-8 objects, and each one can only be clicked once. When an object is clicked, the counter will increment by 1.
Either use querySelectorAll:
var targets = querySelectorAll('a-box')`
for (var i = 0; i < targets.length; i++) { // Add event listeners... }
But better, use a container entity that listens to the click events that bubble up.
<a-entity listener>
<a-box data-raycastable></a-box>
<a-box data-raycastable></a-box>
</a-entity>
<a-entity cursor="rayOrigin: mouse" raycaster="objects: [data-raycastable]"></a-entity>
Component:
AFRAME.registerComponent('listener', {
init: function () {
this.el.addEventListener('click', evt => {
if (evt.target.dataset.wasClicked) { return; }
// evt.target tells you which was clicked.
evt.target.dataset.wasClicked = true;
// Score up.
});
}
});
As a side note, state component is a great place to store your score. https://www.npmjs.com/package/aframe-state-component

What element is jQuery UI draggable being dragged over in an iframe

Here is my code, where I'm trying to detect the element, which a jQuery UI draggable is hovering over. I need to get the element's object and attributes, such as class names (in this case .sortable-grid,.sortable-table,.sortable-row,.sortable-cell).
The answers found here only show how to get the draggable item itself (ui.helper or event.target), but not the element it is hovering above.
The best way to answer would be using the prepared JSFiddle, since my code uses an iframe, which would not work if the full code is posted here:
JSFiddle
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.js"></script>
<div style="background-color:grey;display:inline;cursor:move" id="draggable">DRAG ME</div>
<iframe src="https://fiddle.jshell.net/piglin/UAcC7/1869/show/" id="frame" style="width:100%;overflow:visible" seamless="seamless" scrolling="no"></iframe>
JS:
$("#draggable").draggable({
drag: function(event, ui) {
//Some code here
}
}
It was possible by modifying the function from another answer to fit this purpose. After adapting it to use the contentWindow of the iframe and adding offset calculation it works now.
Solution
function allElementsFromPointIframe(x, y, offsetX, offsetY) {
var element, elements = [];
var old_visibility = [];
while (true) {
element = document.getElementById('frame').contentWindow.document.elementFromPoint(x - offsetX, y - offsetY);
if (!element || element === document.getElementById('frame').contentWindow.document.documentElement) {
break;
}
elements.push(element);
old_visibility.push(element.style.visibility);
element.style.visibility = 'hidden'; // Temporarily hide the element (without changing the layout)
}
for (var k = 0; k < elements.length; k++) {
elements[k].style.visibility = old_visibility[k];
}
elements.reverse();
return elements;
}
var selected = $('');
var tmpColor = 'transparent';
$("#draggable").draggable({
drag: function(event, ui) {
var el = $(allElementsFromPointIframe(event.pageX, event.pageY, $(frame).offset().left, $(frame).offset().top));
var div = $(el).filter('ul, li').not($(this));
selected.css({'backgroundColor': tmpColor});
selected = div.last()
tmpColor = selected.css('backgroundColor');
selected.css({'backgroundColor': 'red'});
console.dir(div);
},
iframeFix: true,
iframeOffset: $('#iframe').offset()
});

How to make an info window clickable?

I have the below code, based on one of the API samples. A click on the map creates a marker. A click on the marker opens up an info window. Now I want a click on the info window to do something. E.g. a click anywhere might close it, as opposed to the little cross in the corner. Or a click on it might open a new URL. Etc.
Unfortunately it seems there is no "click" event for info windows.
The closest I've got is shown as a commented out line below: I wrap my info window content in a div, and give that an onClick. This works, but there is a big border around it. I really want to be able to click anywhere in the info window box.
Is there a way?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Click Test</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
google.maps.visualRefresh = true; //New look visuals.
function initialize() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map-canvas");
if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '400px';
mapdiv.style.height = '600px';
}
var mapOptions = {
zoom:3,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
var infowindow = new google.maps.InfoWindow({
//content: "<div onClick='test1()'>(lat,lng):<br/>"+location.lat()+","+location.lng()+"</div>"
content: "(lat,lng):<br/>"+location.lat()+","+location.lng()
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(marker.get('map'), marker);
infowindow.addListener('click',test1); //Does nothing
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function test1(){alert("test1");}
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
UPDATE:
This image shows the problem when I use a clickable div inside the content (background set to red to show the extent of the region I can make clickable, and also that I can style; if I set a negative margin I just get scrollbars, not a bigger region!). It is the whole white area I want to be clickable, not just that red rectangle.
I decided to use InfoBox found in the Google Maps Utility Library. So in the header add a link to the library. Then replace the new google.maps.InfoWindow() line with this one:
var infowindow = new InfoBox({
closeBoxURL:"",
content: '<div onClick="test1();return false;" style="background:white;opacity:0.8;padding:8px">(lat,lng):<br/>'+
location.lat()+","+location.lng()+"</div>"
});
By setting closeBoxUrl to a blank string I get no close option. I added a large padding just so you can see that clicking right to the edge does indeed work.
You can also do it this way. I also use the boxClass option so the formatting is done in CSS:
var infoContent=document.createElement('div');
infoContent.innerHTML="(lat,lng):<br/>"+location.lat()+","+location.lng();
infoContent.onclick=test1;
var infowindow = new InfoBox({
closeBoxURL:"",
boxClass:"marker_popup",
content: infoContent,
});
(Aside, if doing it this way, on just some browsers it creates a marker below the InfoBox! Simplest fix is to change test1 so it looks like: function test1(event){alert("test1");event.preventDefault();return false;} )
P.S. I chose InfoBox over InfoBubble, as the latter has no documentation, and it had no obvious advantages to compensate for that major flaw! InfoBox has documentation and a reference. (links are for version 1.1.9)

Resources