使用A-Frame从零开始做一个 Web 3D 互动游戏

不用学习新的语言,只有前端现有的知识就可以做AR了。而且是在我们熟悉的Web环境中,不用APP就可以做到。

1. 什么是A-Frame

这个框架的命名跟移动4G的“和”有得一拼,结果都是完美错过所有关键词。
A 会被浏览器忽略 – 是连词符,frame又有太多歧义。如果打出来 aframe 还会被浏览器“智能”拆分成 a frame 变成“一个框架”。
这就导致查资料不容易,沙里淘金的感觉,不过也可能是本身资料就少的缘故。

2017年05月02日更新,孤陋寡闻了,搜索时用引号包含关键词,代表全匹配搜索,搜“A-Frame”可以得到准确的结果。

A-Frame 是一个可以在HTML中创建3d场景的框架,使用Three.js和WebGL来创建VR场景。
不需要了解低层渲染细节,但是A-Frame的说明文档也很长啊。

2. 最简单的demo

https://codepen.io打开代码,在codepen.io预览

<script src="https://aframe.io/releases/0.4.0/aframe.min.js"></script><a-scene>  <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>  <a-box position="-1 0.5 -3" rotation="0 45 0" width="1" height="1" depth="1" color="#4CC3D9"></a-box>  <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder>  <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>    <a-sky color="#ECECEC"></a-sky></a-scene>

代码中的 <a-sky> 就是纯色背景,其他几个看名字就知道是哪个了。
这个demo还可以用鼠标和键盘导航,如果用手机浏览器打开,就是VR效果了。

3. 从头做一个自己的场景

3.1 模板

A-Frame 的所有元素都放在 <a-scene> 中,初始代码如下:

<!DOCTYPE html><html>  <head>    <meta charset="utf-8"/>    <title>Our First A-Frame Experience</title>    <script src="https://aframe.io/releases/0.4.0/aframe.min.js"></script>  </head>  <body>    <a-scene>          </a-scene>  </body></html>

3.2 天空

天空使用的元素是 <a-sky>,代码如下:

<a-sky color="#C500FF"></a-sky>

此时会产生一个紫红色的天空。天空也可以是一个全景图.
flickr 有很多全景图,我们选一个作为背景,比如这一张:

” data-rawwidth=”1600″ data-rawheight=”800″ class=”origin_image zh-lightbox-thumb lazy” width=”1600″ data-original=”https://pic3.zhimg.com/v2-66e7f14a0bf0225bed967deeec5eabb0_r.jpg” data-actualsrc=”https://www.hixianchang.com/wp-content/uploads/2018/20180719/T16109.jpg”>

现在把天空换成这张全景图。

<!DOCTYPE html><html>  <head>    <meta charset="utf-8"/>    <title>Our First A-Frame Experience</title>    <script src="https://aframe.io/releases/0.4.0/aframe.min.js"></script>  </head>  <body>    <a-scene>      <a-sky src="https://c1.staticflickr.com/8/7376/16218590470_468084c950_h.jpg"></a-sky>    </a-scene>  </body></html>

相关新闻