第一个3D案例

 index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入three.js -->
    <!-- <script src="./build/three.js"> -->

    </script>
</head>

<body>
    <div id="webgl" style="margin-top: 100px;margin-left:200px;"></div>
    <!-- 实际开发环境中需要先配置路径 -->
    <script type="importmap">
        {
            "imports": {
                "three": "./build/three.module.js",
                "three/addons/": "../three.js/examples/jsm/"
            }
        }
    </script>
    <script type="module" src="./index.js">


    </script>

</body>

</html>

 index.js

// 按ES6方式的引入threejs
import * as THREE from 'three'

//创建一个三维场景scene
const scene = new THREE.Scene()
//给三维场景添加物体

// 定义一个长方体,长宽高都为100
const geometry = new THREE.BoxGeometry(50, 50, 50)
//定义一个基础网格材质
const material = new THREE.MeshBasicMaterial({
    color: 0x00ffff,//红色材质
    transparent: true,//开启透明
    opacity: 0.5,//设置透明度
})
//创建一个网格模型:表示生活中的物体
const mesh = new THREE.Mesh(geometry, material)
//设置网格模型(物体)在三维空间中的位置坐标,默认是坐标原点
mesh.position.set(0, 70, 0)

//通过.add方法=>把mesh添加到三维场景中
scene.add(mesh)

// console.log('mesh', mesh)

//创建一个三位坐标轴
// AxesHelper:辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(150);
// 将坐标轴对象添加到三维场景中
scene.add(axesHelper);

//定义相机输出画布的canvas尺寸
const width = 800;
const height = 500;
//设置相机的四个参数

//创建一个透视投影相机对象
const camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 2000);
//设置相机位置
camera.position.set(200, 200, 200)
//相机的视线 观察目标点的坐标
camera.lookAt(0, 0, 0);//坐标原点
// camera.lookAt(0, 10, 0);//y轴上一点
// camera.lookAt(mesh.position);//指向网格模型


//创建一个WebGL渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(width, height);//canvas画布宽高度
renderer.render(scene, camera);//渲染场景和相机,类比相机的拍照动作
//把渲染结果canvas画布,也就是照片渲染到前端页面上
// document.body.appendChild(renderer.domElement)

document.getElementById('webgl').appendChild(renderer.domElement)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值