我已经从它的官方站点下载了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>错误截图:

发布于 2021-06-08 05:47:00
原因
file://无法工作,因为您使用的是module,这是ES6标准。
见这里:
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>然后在http-server中运行root-path
cd root-path
http-server .默认情况下,http-server绑定到端口8080。现在您可以在http://localhost:8080/running-basic-threejs上访问您的站点了。
https://stackoverflow.com/questions/67881363
复制相似问题