您现在的位置是:首页 > 开发类 > Web开发Web开发

使用vue学习three.js之加载和使用纹理-设置material.normalMap属性使用法向贴图创建表面不同凹凸程度的三维物体

2021-06-05 09:14:12Web开发人已围观

简介使用法向贴图创建凹凸和皱纹1.demo效果2. 知识要点2.1 法向贴图2.2 使用法向贴图3. 实现要点2.2 创建凹凸贴图的物体2.3 创建普通贴图的物体3. demo代码1.demo效果2. 知识要点2.1 法向贴图法向贴图 保存的是每个像素的法向量,这样的好处是使用非常少的顶点和面就可以创建出有丰富细节的模型2.2 使用法向贴图使用法向贴图的方法和使用凹凸贴图一样,只需要将material的 normalMap 属性设置成一个法向纹理即可,同时也可以通过 mormalScale 属性设

使用法向贴图创建表面不同凹凸程度的三维物体

  • 1.demo效果
  • 2. 知识要点
    • 2.1 法向贴图
    • 2.2 使用法向贴图
  • 3. 实现要点
    • 3.1 创建模型
    • 3.2 模型贴图与法向贴图更新
    • 3.3 点光源绕物体8字型运动
  • 3. demo代码

1.demo效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 知识要点

2.1 法向贴图

法向贴图 保存的是每个像素的法向量,这样的好处是使用非常少的顶点和面就可以创建出有丰富细节的模型

2.2 使用法向贴图

使用法向贴图的方法和使用凹凸贴图一样,只需要将material的 normalMap 属性设置成一个法向纹理即可,同时也可以通过material的 mormalScale 属性设置法向纹理的的凹凸程度,
设置方法如下:

//设置法线贴图
const normal = new THREE.TextureLoader().load(url)
this.cube2.material.normalMap = normal

//设置法向贴图的凹凸程度
material.normalScale.set(x, y)

3. 实现要点

3.1 创建模型

通过demo效果可知,每次切换页面中展示两个模型一个使用法向贴图,一个没有,先来说说如何创建带法向贴图和不带法向贴图的模型

//创建网格对象
createMesh(geom, imageFile, normal) {
  // 设置法向贴图
  const publicPath = process.env.BASE_URL
  const texture = new THREE.TextureLoader().load(
    `${publicPath}textures/general/` + imageFile
  )
  const material = new THREE.MeshPhongMaterial()
  material.map = texture

  // 设置法向贴图的凹凸程度
  if (normal) {
    const normalMap = new THREE.TextureLoader().load(
      `${publicPath}textures/general/` + normal
    )
    material.normalMap = normalMap
  }
  const mesh = new THREE.Mesh(geom, material)
  return mesh
}
// 创建模型
createModels() {
  this.cube1 = this.createMesh(
    new THREE.BoxGeometry(15, 15, 15),
    'bathroom.jpg'
  )
  this.cube1.rotation.y = -0.5
  this.cube1.position.x = 12
  this.scene.add(this.cube1)

  this.cube2 = this.createMesh(
    new THREE.BoxGeometry(15, 15, 15),
    'bathroom.jpg',
    'bathroom-normal.jpg'
  )
  this.cube2.rotation.y = 0.5
  this.cube2.position.x = -12
  this.scene.add(this.cube2)

  this.createFloor()
}

3.2 模型贴图与法向贴图更新

每次切换不同的贴图时,模型的纹理贴图和法向贴图都需要更新,如何实现参照以下代码

propertiesChange() {
  const publicPath = process.env.BASE_URL

  // 更新物体表面纹理贴图
  const texture = new THREE.TextureLoader().load(
    `${publicPath}textures/general/` + this.properties.textureType + '.jpg'
  )
  this.cube1.material.map = texture
  this.cube2.material.map = texture

  // 更新法向贴图
  const normal = new THREE.TextureLoader().load(
    `${publicPath}textures/general/` +
      this.properties.textureType +
      '-normal.jpg'
  )
  this.cube2.material.normalMap = normal

  // 更新法向贴图的凹凸程度
  this.cube2.material.normalScale.set(
    this.properties.normalScale.value,
    this.properties.normalScale.value
  ) // normalScale(x,y)
}

3.3 点光源绕物体8字型运动

// 创建球形光源
createSmallSphereLight() {
  const sphereLight = new THREE.SphereGeometry(0.2)
  const sphereLightMaterial = new THREE.MeshBasicMaterial({
    color: 0xac6c25
  })
  this.sphereLightMesh = new THREE.Mesh(sphereLight, sphereLightMaterial)
  this.sphereLightMesh.castShadow = true

  this.sphereLightMesh.position = new THREE.Vector3(3, 3, 3)
  this.scene.add(this.sphereLightMesh)
}
//球形点光源动画函数
smallShpereLightAnimation() {
  if (this.phase > 2 * Math.PI) {
    this.invert = this.invert * -1
    this.phase -= 2 * Math.PI
  } else {
    this.phase += 0.03
  }

  this.sphereLightMesh.position.z = +(21 * Math.sin(this.phase))
  this.sphereLightMesh.position.x = -14 + 14 * Math.cos(this.phase)

  if (this.invert < 0) {
    const pivot = 0
    this.sphereLightMesh.position.x =
      this.invert * (this.sphereLightMesh.position.x - pivot) + pivot
  }

  this.pointLight.position.copy(this.sphereLightMesh.position) // 把小球光源的坐标复制给点光源
}

3. demo代码

<template>
  <div>
    <div id="container" />
    <div class="controls-box">
      <section>
        <el-row>
          <el-checkbox v-model="properties.rotate">
            rotate
          </el-checkbox>
        </el-row>
        <el-row>
          <div v-for="(item,key) in properties" :key="key">
            <div v-if="item&&item.name!=undefined">
              <el-col :span="8">
                <span class="vertice-span">{{ item.name }}</span>
              </el-col>
              <el-col :span="13">
                <el-slider v-model="item.value" :min="item.min" :max="item.max" :step="item.step" :format-tooltip="formatTooltip" @change="propertiesChange" />
              </el-col>
              <el-col :span="3">
                <span class="vertice-span">{{ item.value }}</span>
              </el-col>
            </div>
          </div>
        </el-row>
        <el-row>
          <el-col :span="8" class="label-col">
            <label>texture</label>
          </el-col>
          <el-col :span="16">
            <el-select v-model="properties.textureType" placeholder="请选择" @change="propertiesChange">
              <el-option v-for="item in texturesOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
        </el-row>
      </section>
    </div>
  </div>
</template>

<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
export default {
  data() {
    return {
      texturesOptions: [
        {
          value: 'bathroom',
          label: 'bathroom'
        },
        {
          value: 'plaster',
          label: 'plaster'
        },
        {
          value: 'metal-floor',
          label: 'metal-floor'
        }
      ],
      properties: {
        normalScale: {
          name: 'normalScale',
          value: 0.2,
          min: -2,
          max: 2,
          step: 0.1
        },
        textureType: 'bathroom',
        rotate: false
      },
      cube1: null,
      cube2: null,
      sphereLightMesh: null,
      pointLight: null,
      camera: null,
      scene: null,
      renderer: null,
      controls: null,
      invert: 1,
      phase: 0
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    formatTooltip(val) {
      return val
    },

    // 初始化
    init() {
      this.createScene() // 创建场景
      this.createModels() // 创建模型
      this.createLight() // 创建光源
      this.createCamera() // 创建相机
      this.createRender() // 创建渲染器
      this.createControls() // 创建控件对象
      this.render() // 渲染
    },
    // 创建场景
    createScene() {
      this.scene = new THREE.Scene()
    },
    // 创建模型
    createModels() {
      this.cube1 = this.createMesh(
        new THREE.BoxGeometry(15, 15, 15),
        'bathroom.jpg'
      )
      this.cube1.rotation.y = -0.5
      this.cube1.position.x = 12
      this.scene.add(this.cube1)

      this.cube2 = this.createMesh(
        new THREE.BoxGeometry(15, 15, 15),
        'bathroom.jpg',
        'bathroom-normal.jpg'
      )
      this.cube2.rotation.y = 0.5
      this.cube2.position.x = -12
      this.scene.add(this.cube2)

      this.createFloor()
    },
    //创建网格对象
    createMesh(geom, imageFile, normal) {
      // 设置法向贴图
      const publicPath = process.env.BASE_URL
      const texture = new THREE.TextureLoader().load(
        `${publicPath}textures/general/` + imageFile
      )
      const material = new THREE.MeshPhongMaterial()
      material.map = texture

      // 设置法向贴图的凹凸程度
      if (normal) {
        const normalMap = new THREE.TextureLoader().load(
          `${publicPath}textures/general/` + normal
        )
        material.normalMap = normalMap
      }
      const mesh = new THREE.Mesh(geom, material)
      return mesh
    },
    createFloor() {
      const publicPath = process.env.BASE_URL
      const floorTex = new THREE.TextureLoader().load(
        `${publicPath}textures/general/floor-wood.jpg`
      )
      const plane = new THREE.Mesh(
        new THREE.BoxGeometry(200, 100, 0.1, 30),
        new THREE.MeshPhongMaterial({
          color: 0x3c3c3c,
          map: floorTex
        })
      )
      plane.position.y = -7.5
      plane.rotation.x = -0.5 * Math.PI
      this.scene.add(plane)
    },
    // 创建光源
    createLight() {
      // 环境光
      const ambientLight = new THREE.AmbientLight(0x242424, 0.1) // 创建环境光
      this.scene.add(ambientLight) // 将环境光添加到场景

      const spotLight = new THREE.SpotLight(0xffffff) // 创建聚光灯
      spotLight.position.set(0, 30, 30)
      spotLight.intensity = 1.2
      this.scene.add(spotLight)

      // 点光源
      const pointColor = '#ff5808'
      this.pointLight = new THREE.PointLight(pointColor)
      //this.pointLight.distance = 0
      //this.pointLight.intensity = 0.5
      this.scene.add(this.pointLight)

      this.createSmallSphereLight()
    },
    // 创建球形光源
    createSmallSphereLight() {
      const sphereLight = new THREE.SphereGeometry(0.2)
      const sphereLightMaterial = new THREE.MeshBasicMaterial({
        color: 0xac6c25
      })
      this.sphereLightMesh = new THREE.Mesh(sphereLight, sphereLightMaterial)
      this.sphereLightMesh.castShadow = true

      this.sphereLightMesh.position = new THREE.Vector3(3, 3, 3)
      this.scene.add(this.sphereLightMesh)
    },
    // 创建相机
    createCamera() {
      const element = document.getElementById('container')
      const width = element.clientWidth // 窗口宽度
      const height = element.clientHeight // 窗口高度
      const k = width / height // 窗口宽高比
      // PerspectiveCamera( fov, aspect, near, far )
      this.camera = new THREE.PerspectiveCamera(45, k, 0.1, 1000)
      this.camera.position.set(0, 12, 38) // 设置相机位置

      this.camera.lookAt(new THREE.Vector3(0, 0, 0)) // 设置相机方向
      this.scene.add(this.camera)
    },
    // 创建渲染器
    createRender() {
      const element = document.getElementById('container')
      this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })
      this.renderer.setSize(element.clientWidth, element.clientHeight) // 设置渲染区域尺寸
      this.renderer.shadowMap.enabled = true // 显示阴影
      // this.renderer.shadowMap.type = THREE.PCFSoftShadowMap
      this.renderer.setClearColor(0xeeeeee, 1) // 设置背景颜色
      element.appendChild(this.renderer.domElement)
    },

    propertiesChange() {
      const publicPath = process.env.BASE_URL

      // 更新物体表面纹理贴图
      const texture = new THREE.TextureLoader().load(
        `${publicPath}textures/general/` + this.properties.textureType + '.jpg'
      )
      this.cube1.material.map = texture
      this.cube2.material.map = texture

      // 更新法向贴图
      const normal = new THREE.TextureLoader().load(
        `${publicPath}textures/general/` +
          this.properties.textureType +
          '-normal.jpg'
      )
      this.cube2.material.normalMap = normal

      // 更新法向贴图的凹凸程度
      this.cube2.material.normalScale.set(
        this.properties.normalScale.value,
        this.properties.normalScale.value
      ) // normalScale(x,y)
    },

    updateRotation() {
      if (this.properties.rotate) {
        this.cube1.rotation.y += 0.01
        this.cube2.rotation.y -= 0.01
      }
    },
    //球形点光源动画函数
    smallShpereLightAnimation() {
      if (this.phase > 2 * Math.PI) {
        this.invert = this.invert * -1
        this.phase -= 2 * Math.PI
      } else {
        this.phase += 0.03
      }

      this.sphereLightMesh.position.z = +(21 * Math.sin(this.phase))
      this.sphereLightMesh.position.x = -14 + 14 * Math.cos(this.phase)

      if (this.invert < 0) {
        const pivot = 0
        this.sphereLightMesh.position.x =
          this.invert * (this.sphereLightMesh.position.x - pivot) + pivot
      }

      this.pointLight.position.copy(this.sphereLightMesh.position) // 把小球光源的坐标复制给点光源
    },

    render() {
      this.smallShpereLightAnimation()
      this.updateRotation()
      this.renderer.render(this.scene, this.camera)
      requestAnimationFrame(this.render)
    },
    // 创建控件对象
    createControls() {
      this.controls = new OrbitControls(this.camera, this.renderer.domElement)
    }
  }
}
</script>

<style>
#container {
  position: absolute;
  width: 100%;
  height: 100%;
}
.controls-box {
  position: absolute;
  right: 5px;
  top: 5px;
  width: 300px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #c3c3c3;
}
.label-col {
  padding: 8px 5px;
}

.vertice-span {
  line-height: 38px;
  padding: 0 2px 0 10px;
}
</style>

文章来源:https://blog.csdn.net/qw8704149/article/details/117485044

Tags:three.js 使用法向贴图 不同凹凸程度表面 三维web 

很赞哦! ()

文章评论

留言与评论(共有 0 条评论)
   
验证码:

本栏推荐

站点信息

  • 文章统计247968篇文章
  • 浏览统计18356次浏览
  • 评论统计1个评论
  • 标签管理标签云
  • 统计数据:统计代码
  • 微信公众号:扫描二维码,关注我们