gpt4 book ai didi

javascript - 如何使用 aframe 以编程方式创建场景

转载 作者:行者123 更新时间:2023-12-03 02:06:12 25 4
gpt4 key购买 nike

我是js和html新手,我想进入Aframe。我想从声明式形式创建场景转为使用 js 以编程方式创建场景:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript - A-Frame School</title>
<meta name="description" content="JavaScript - A-Frame School">
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>

</head>
<body>
<a-scene school-playground>
<a-box position="-1 0 -4.25" rotation="0 45 0" color="red" ></a-box>

<a-sky color="#ECECEC"></a-sky>
</a-scene>
</body>
</html>

类似的事情:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript - A-Frame School</title>
<meta name="description" content="JavaScript - A-Frame School">
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script>
AFRAME.registerComponent('school-playground', {

init: function () {

var body = document.querySelector('body');
var sceneEl = document.createElement("a-scene");
var body = document.querySelector('body');
sceneEl.setAttribute("embedded", true);
sceneEl.style.height="700px";
sceneEl.style.width="100%";
sceneEl.setAttribute("school-playground", "");

var myBox = document.createElement('a-box');
myBox.setAttribute('position', {x:-1, y:0, z:-4})
myBox.setAttribute('rotation', {x:0,y:45, z:0}
myBox.setAttribute('color', "red");
sceneEl.appendChild(myBox);
body.appendChild(sceneEl);
//I also tried document.body.appendChild(sceneEl);
}
});
</script>
</head>
<body>

</body>
</html>

似乎不可能正确地做到这一点。我需要保持场景静态定义吗?

感谢您的帮助。

最佳答案

组件在附加到实体 ( https://aframe.io/docs/0.8.0/introduction/writing-a-component.html#using-property-data-from-a-lifecycle-handler ) 时初始化。您的组件刚刚注册,但未与任何实体关联,因此 init 方法不会运行。您可以像 JavaScript 中的任何其他常规 DOM 组件一样以编程方式创建场景,与您所做的类似,但请记住在组件外部执行此操作并将场景附加到文档中:

 var sceneEl = document.createElement("a-scene");
...
document.body.appendChild(sceneEl);

您还可以定义您的<a-scene>静态标记然后填充场景:

sceneEl = document.querySelector("a-scene");
... create and append scene entities ...
sceneEl.appendChild(yourEntity);

我还建议将您的 A-Frame 版本升级到 0.8.0

关于 Glitch 的完整可运行示例:https://glitch.com/edit/#!/conscious-way

<!DOCTYPE html>
<html>
<head>
<title>Hello, WebVR! - A-Frame</title>
<meta name="description" content="Hello, WebVR! - A-Frame">
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
</head>
<body>
</body>
<script>
var sceneEl = document.createElement('a-scene');
sceneEl.setAttribute('background', {color: 'red'});
var cubeEl = document.createElement('a-box');
cubeEl.setAttribute('color', 'blue');
cubeEl.setAttribute('position', '0 1.5 -2');
sceneEl.appendChild(cubeEl);
document.body.appendChild(sceneEl);
</script>
</html>

关于javascript - 如何使用 aframe 以编程方式创建场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49797418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com