【发布时间】:2021-04-07 08:23:39
【问题描述】:
我正在尝试按照此处的教程进行操作:https://threejs.org/docs/#manual/en/introduction/Creating-a-scene,而我的浏览器只显示了一个白色窗口。我尝试将文件分离为 js 和 html 文件。
我已经尝试过的:
- 在脚本标签中添加/删除
nomodule参数 - 运行本地实时服务器
这是我的代码:
我的 index.html 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script nomodule src="js/main.js"></script>
<script>
// Our Javascript will go here.
</script>
</body>
</html>
我的 js 文件名为 main.js,位于“js”文件夹中。我通过 npm 安装了 Three.js。
import * as THREE from 'three'
//import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth, window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({color:0x00ff00});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
const animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
反之示例代码:
<!DOCTYPE html>
<html>
<head>
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="js/three.js"></script>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
const animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
animate();
</script>
</body>
</html>
【问题讨论】:
-
这能回答你的问题吗? What’s the purpose of the HTML “nomodule” attribute for script elements if the default is text/javascript?您的脚本被忽略,因为您添加了
nomodule -
不,不幸的是它没有。如果我删除
nomodule,我会在控制台中收到一个错误:Uncaught SyntaxError: import declarations may only appear at top level of a module我看到 nomodule 参数会让这个错误消失,但似乎有一个不同的问题 -
将
type=“module”添加到脚本标签而不是nomodule 时会发生什么? -
在这种情况下,Firefox 向我显示一条错误消息,指出“同源规则”禁止从文件中读取外部资源。
TypeError: Cross-origin script load denied by Cross-Origin Resource Sharing policy.
标签: javascript html three.js