Skip to content

Instantly share code, notes, and snippets.

@edmondyip
Created October 30, 2019 07:52
Show Gist options
  • Select an option

  • Save edmondyip/b6735e462ff08a5328b20f6df2e69a28 to your computer and use it in GitHub Desktop.

Select an option

Save edmondyip/b6735e462ff08a5328b20f6df2e69a28 to your computer and use it in GitHub Desktop.
Threejs in Vue
<template lang="pug">
#three
</template>
<script>
export default {
mounted() {
this.init();
},
methods: {
init() {
const {
runTime, canvasHeight, canvasWidth, scene, renderer, camera, box // 定義各種共用的數據
} = this;
runTime();
},
runTime() {
this.canvasHeight = document.getElementById("three").offsetHeight; // 將 canvas 高度設定成 #three 的高度
this.canvasWidth = document.getElementById("three").offsetWidth; // 將 canvas 高度設定成 #three 的高度
this.createScene(); // 建立場景
this.createLights(); // 建立燈光
this.createObject(); // 建立物件
window.addEventListener('resize', this.windowResize.bind(this), false); // 監視視窗大小變化
this.renderScene(); // 開始運作
},
createScene() {
this.scene = new this.$THREE.Scene(); // 建立新場景
this.camera = new this.$THREE.PerspectiveCamera(45, this.canvasWidth / this.canvasHeight, 1, 1000); // 建立鏡頭
this.camera.position.set(150, 150, 150);
this.scene.add(this.camera); // 把鏡頭加到場景
this.renderer = new this.$THREE.WebGLRenderer({ // 建立渲染器
antialias: true // 反鋸齒開啟
});
this.renderer.setSize(this.canvasWidth, this.canvasHeight); // 設定渲染器大小跟 canvas 一樣
this.renderer.setPixelRatio(window.devicePixelRatio); // 設定渲染器比例跟螢幕一樣
document.getElementById("three").appendChild(this.renderer.domElement); // 把渲染器加到 #three
},
createLights() {
const Light = new this.$THREE.HemisphereLight(0xffffff, 0x080820, 0.8); // 設定環境光源
this.scene.add(Light); // 把光源加到場景
},
createObject() {
const cubeGeometry = new this.$THREE.BoxBufferGeometry(100, 100, 100, 5, 5, 5); // 建立長闊高都是 100,每邊由 5 個多邊形組成的方體
const cubeMaterial = new this.$THREE.MeshLambertMaterial({ // 建立材質
color: 0xffeeee, // 顏色
wireframe: true, // 外框
});
this.box = new this.$THREE.Mesh(cubeGeometry, cubeMaterial); // 設定box的形狀及材質
this.box.position.set(60, 0, -50); // 設定box的位置
this.scene.add(this.box); // 把box加到場景
},
windowResize() {
this.canvasHeight = document.getElementById("three").offsetHeight; // 重新取得長闊
this.canvasWidth = document.getElementById("three").offsetWidth;
this.renderer.setSize(this.canvasWidth, this.canvasHeight); // 重設長闊
this.camera.aspect = this.canvasWidth / this.canvasHeight;
this.camera.updateProjectionMatrix(); // 更新鏡頭視點
},
renderScene() {
requestAnimationFrame(this.renderScene); // 產生動畫
this.box.rotation.y += 0.005; // 令box的Y軸在每格動畫中轉動一點點
this.renderer.render(this.scene, this.camera);
},
}
</script>
<style lang="stylus" scoped>
#three
width 100%
height 100%
background #ffffff
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment