我已经从其官方网站下载了 Three.js,并且尝试运行非常基本的文件,但出现了奇怪的错误,但是当我用 CDN 替换 Three.js 文件导入时> 它开始工作。请帮助我从本地启动文件。
<html>
<head>
<title>1 - First Scene</title>
<link rel = "stylesheet" href = "Style.css">
<!-- <script src = "../three.js-master/src/Three.js"></script>--> <!-- This doesn't work, I get errors -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js"></script> <!-- This works -->
</head>
<body>
</body>
</html>
<script >
let scene, camera, renderer;
// set up the environment -
// initiallize scene, camera, objects and renderer
let init = function() {
// create the scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xababab);
// create an locate the camera
camera = new THREE.PerspectiveCamera(30,
window.innerWidth / window.innerHeight,
1, 1000);
camera.position.z = 5;
// create the renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
};
// main animation loop - calls 50-60 in a second.
let mainLoop = function() {
console.log("Hello");
renderer.render(scene, camera);
requestAnimationFrame(mainLoop);
};
///////////////////////////////////////////////
init();
mainLoop();
</script>
最佳答案
原因
file://
不起作用,因为您使用的是 ES6 标准的 module
。
看这里:
Access to Script at ' from origin 'null' has been blocked by CORS policy
解决方案
托管本地服务器并使用 http://localhost URL 访问此 HTML。
我建议使用http-server
只需安装
npm install -g http-server
假设您的文件夹如下所示:
|- root-path
|- three.js-master
|- running-basic-threejs
|- index.html
并将type="module"
添加到您的脚本
<script type="module">
import * as THREE from '../three.js-master/src/Three.js'
// ...
</script>
然后在root-path
中运行http-server
cd root-path
http-server .
默认情况下,http-server
绑定(bind)到端口 8080
。
现在您可以通过 http://localhost:8080/running-basic-thirdjs
关于javascript - 运行基本的 Three.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67881363/