Three.js로 3D 입방체를 삽입한 Buton 만들기
18097 단어 TypeScriptthreejstech
완성물
방법
Vite를 사용하여 프로젝트를 만듭니다.
npm init vite@latest my-vite-3dbutton --template vanilla-ts
Three.js와 형식 정의 파일을 설치합니다.npm install --save three @types/three
index.파일을 열고 button 및 Canvas를 추가합니다.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">
<button>
<canvas />
</button>
</div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
main.ts 파일을 열고 첫 줄 이외의 내용을 삭제하고 다시 씁니다.main.ts
import './style.css'
import * as THREE from 'three';
function init() {
// Button取得, Buttonの縦幅・横幅をwidth,height変数に代入
const button = document.querySelector('button') as HTMLButtonElement;
const width = button.clientWidth;
const height = button.clientHeight;
// Three.js側の処理
const renderer = new THREE.WebGLRenderer({
canvas: document.querySelector('canvas') as HTMLCanvasElement
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(width, height);
// シーン作成
const scene = new THREE.Scene();
// カメラ作成
const camera = new THREE.PerspectiveCamera(45, width / height);
camera.position.set(0, 0, 1000);
// 立方体の3Dモデルを作ってシーンに追加
const geometry = new THREE.BoxGeometry(400, 400, 400);
const material = new THREE.MeshNormalMaterial();
const box = new THREE.Mesh(geometry, material);
scene.add(box);
// レンダリングする用のTick関数
function Tick() {
requestAnimationFrame(Tick);
renderer.render(scene, camera);
}
Tick();
}
window.onload = init;
이 느낌으로 3D 모델의 입방체를 버튼에 표시합니다.발전시키다
이렇게 하면 재미가 없으니 안의 입방체를 좀 돌려라.
먼저 회전할 각도의 변수를 준비합니다.
4
let rotaion: number = 0.005;
Tick 함수를 실행할 때마다 box는 회전합니다.// レンダリングする用のTick関数
function Tick() {
requestAnimationFrame(Tick);
box.rotation.y += rotaion;
renderer.render(scene, camera);
}
버튼 위에 커서를 놓으면 회전 속도를 변경합니다.
CSS 버튼의 크기를 변경해 보십시오.
button.onmouseenter = () => {
rotaion = 0.01;
}
button.onmouseleave = () => {
rotaion = 0.005;
}
style.css#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
button {
transition-property: transform;
transition-duration: 0.5s;
}
button:hover {
transform: scale(1.1);
}
Reference
이 문제에 관하여(Three.js로 3D 입방체를 삽입한 Buton 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/utamono832/articles/51eb8804bae9d8텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)