javascript HTML和Three.js画布未显示在页面上

whhtz7ly  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(206)

我试图学习如何使用three.js,但在我的html文件中,标记不会显示在我的页面上。
下面是我的HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Three JS</title>
</head>
<body>
    <canvas class="webgl"></canvas>
    <script src="/main.js"></script>
</body>
</html>

下面是我的javascript代码:

import * as THREE from 'three'

const scene = new THREE.Scene()

const geometry = new THREE.SphereGeometry(3, 64, 64)
const material = new THREE.MeshStandardMaterial({
    color: '#00ff83'
})
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)

const camera = new THREE.PerspectiveCamera(45)
scene.add(camera)

const canvas = document.querySelector(".webgl")
const renderer = new THREE.WebGLRenderer({canvas})
renderer.setSize(800, 600)
renderer.render(scene, camera)

我知道相机和物体在同一个点上,但我仍然应该看到一个黑色的方块作为我的画布。

rta7y2nd

rta7y2nd1#

有两项需要更改。

1源CDNimport更常用

2相机-我不知道PespectiveCamera,但你的设置不工作。我从这里复制。

HTML代码

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Three JS</title>
</head>

<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.148.0/three.min.js"></script>
    <canvas class="webgl"></canvas>
    <script src="./main.js"></script>
</body>

</html>

脚本代码为main.js

const scene = new THREE.Scene()

const geometry = new THREE.SphereGeometry(3, 64, 64);
const material = new THREE.MeshBasicMaterial({
    color: '#00ff83'
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // updated
scene.add(camera)

const canvas = document.querySelector(".webgl")
const renderer = new THREE.WebGLRenderer({canvas})
renderer.setSize(800, 600)
camera.position.z = 5;  // added
renderer.render(scene, camera);

使用live server生成VS代码

相关问题