入门three.js绘图

107 阅读1分钟

Snipaste_2022-07-07_17-32-22.png

three.js是javascript的一个库,可以创建2d或3d的图形,相信大家都不陌生,很多花里胡哨666的效果都是用three.js实现的.我这里通过一个小尝试入门一手three.js(ps:虽然是个截图,不过是可以旋转的)

首先梳理先实现过程

1.准备一个项目(我这里通过vite创建),再准备张地球的照片(globe.jpeg),创建index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/main.js"></script>
  </body>
</html>

2.通过引入three.js库进行配置几何体,创建main.js

import './style.css'
// 导入整个 three.js核心库
import * as THREE from 'three';

// 使用three.js一定要有三个对象
// scene === container 场景 容器
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);

// 渲染到DOM的canvas中
document.body.appendChild(renderer.domElement);

// 加载模型 几何体
const geometry = new THREE.SphereGeometry(5, 50, 50);
const material = new THREE.MeshBasicMaterial({
  map: new THREE.TextureLoader().load("globe.jpeg")
});
const sphere = new THREE.Mesh(geometry, material);

camera.position.z = 20;
scene.add(sphere);

const mouse = {
  x: undefined,
  y: undefined,
}

document.addEventListener("mousemove", (e) => {
  mouse.x = (e.clientX / window.innerWidth) * 2
  mouse.y = (e.clientY / window.innerHeight) * 2
  // console.log(mouse)
})

function animate() {
  requestAnimationFrame(animate);
  sphere.rotation.y += 0.01;
  sphere.rotation.x = mouse.x;
  sphere.rotation.z = mouse.y;
  renderer.render(scene, camera);
}
animate();

Vite-App-Google-Chrome-2022-07-unscreen.gif

最后运行项目,简单的入门就绘制成功,由于动图背景做了虚化处理QAQ,虽然很简单有手就行,不过接下来会继续学习,实现出更加炫酷的效果呈现出来