首页 > 解决方案 > 三.js | HTML 元素不显示

问题描述

我有一个涉及球体的简单 THREE.js 应用程序。h2我还想在球体附近显示一些标签中的文本。但是在当前配置中,文本似乎根本没有出现在页面上。

这是我的代码。

style.css

canvas {
position: fixed;
top: 0;
left: 0;
}

h2 {
color: red;
text-transform: uppercase;
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="favicon.svg" />
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="/style.css" />
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
</head>
<body>
    <canvas class="app"></canvas>
    <h2>Feel the sphere</h2>
</body>
<script type="module" src="/main.js"></script>
</html>

main.js

import * as THREE from 'three';
import './style.css';


// TEXTURE LOADER
const textureLoader = new THREE.TextureLoader()
const normalMap = textureLoader.load('./golf-map.png')

// SCENE
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x292929)

// CAMERA
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(0,0,2)

// RENDERER
const renderer = new THREE.WebGLRenderer({
    canvas: document.querySelector('.app'),
})
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)

// SPHERE
const sphereGeometry = new THREE.SphereBufferGeometry(0.5, 64, 64)
const sphereMaterial = new THREE.MeshStandardMaterial()
sphereMaterial.normalMap = normalMap
sphereMaterial.metalness = 0.7
sphereMaterial.roughness = 0.2
sphereMaterial.color = new THREE.Color(0x292929)
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial)
scene.add(sphere)

// // LIGHTING
const pointLight1 = new THREE.PointLight(0xff0000)
pointLight1.position.set(-2.13, 3, -1.98)
pointLight1.intensity = 6.8
scene.add(pointLight1)

const pointLight2 = new THREE.PointLight(0x34e8eb)
pointLight2.position.set(2.13, -3, -1.98)
pointLight2.intensity = 6.8
scene.add(pointLight2)


// // RENDER LOOP
function animate() {


    requestAnimationFrame(animate);
    renderer.render(scene, camera)
}

animate()

球体

如上图所示,我得到了所需的球体。但是h2标签内容是无处可见的。请帮忙。

标签: javascriptthree.js

解决方案


推荐阅读