前面的几篇文章分别写了基于位置的AR和基于图像标记的AR,这一篇文章我们在之前的基础上面增加一些交互元素,也就是用html+css+方法的方式来给页面增加一些可以互动的东西。
其实原理还是很简单的,只是用到了一些html+css的东西。下面还是先拿官方的例子来看一下。
<!DOCTYPE html>
<html>
<script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
<!-- we import arjs version without NFT but with marker + location based support -->
<script src="https://raw.githack.com/AR-js-org/AR.js/master/aframe/build/aframe-ar.js"></script>
<body style="margin : 0px; overflow: hidden;">
<a-scene embedded arjs>
<a-marker preset="hiro">
<a-entity
position="0 0 0"
scale="0.05 0.05 0.05"
gltf-model="https://arjs-cors-proxy.herokuapp.com/https://raw.githack.com/AR-js-org/AR.js/master/aframe/examples/image-tracking/nft/trex/scene.gltf"
></a-entity>
</a-marker>
<a-entity camera></a-entity>
</a-scene>
</body>
</html>
首先上面的这个代码大家应该看着比较熟悉,就是一个简单的基于标记的ar示例,其结构也是html-body这种基础结构,我们是可以在<body>标签里面添加一些html元素的。
比如增加一个按钮:
<div class="buttons">
<button class="say-hi-button"></button>
</div>
但是仅仅直接增加是不行的,还需要给元素加上一些css样式,最重要的就是绝对定位,来定位按钮的位置,同时想要增加交互的话还可以绑定一些js方法,这些都算是前端基础,最后增加完之后,我们得到了以下代码:
<!DOCTYPE html>
<html>
<script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
<!-- we import arjs version without NFT but with marker + location based support -->
<script src="https://raw.githack.com/AR-js-org/AR.js/master/aframe/build/aframe-ar.js"></script>
<script>
window.onload = function () {
document
.querySelector(".say-hi-button")
.addEventListener("click", function () {
// here you can change also a-scene or a-entity properties, like
// changing your 3D model source, size, position and so on
// or you can just open links, trigger actions...
alert("Hi there!");
});
};
</script>
<style>
.buttons {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 5em;
display: flex;
justify-content: center;
align-items: center;
z-index: 10;
}
.say-hi-button {
padding: 0.25em;
border-radius: 4px;
border: none;
background: white;
color: black;
width: 4em;
height: 2em;
}
</style>
<body style="margin : 0px; overflow: hidden;">
<div class="buttons">
<button class="say-hi-button">SAY HI!</button>
</div>
<a-scene embedded arjs>
<a-marker preset="hiro">
<a-entity
position="0 0 0"
scale="0.05 0.05 0.05"
gltf-model="https://arjs-cors-proxy.herokuapp.com/https://raw.githack.com/AR-js-org/AR.js/master/aframe/examples/image-tracking/nft/trex/scene.gltf"
></a-entity>
</a-marker>
<a-entity camera></a-entity>
</a-scene>
</body>
</html>
部署到服务器上面,试着运行一下,就会发现在界面上出现了一个按钮,点击会跳出弹框。
注意:上面引用的js文件需要梯子才能正常访问,想要国内正常访问的话需要下载到本地进行引用,具体下载的方法在前面的文章里面已经提过了,官方的github上面都有,需要的话大家可以去看下我前面的文章。