three.js在canvas画布上生成噪音图,然后创建凹凸贴图(vue中使用three.js79)

1.demo效果

在这里插入图片描述

2. 实现要点

2.1 引入噪音函数库

在public目录下的index.html文件中通过< script >标签引入perlin.js 文件

<script type="text/javascript" src="./libs/perlin.js"></script>

2.2在画布上绘制噪音图

这里首先创建一个canvas标签,追加到DOM上,然后通过噪音函数生成噪音图

addCanvas() {
  const publicPath = process.env.BASE_URL
  this.canvas = document.createElement('canvas')
  this.canvas.setAttribute('width', 256)
  this.canvas.setAttribute('height', 256)
  this.canvas.setAttribute(
    'style',
    'position: absolute; x:0; y:0; bottom: 0px'
  )
  document.getElementById('canvas-output').appendChild(this.canvas)

  const ctx = this.canvas.getContext('2d')
  const date = new Date()
  const pn = new Perlin('rnd' + date.getTime())

  this.fillWithPerlin(pn, ctx)
},

//对canvas噪音处理
fillWithPerlin(perlin, ctx) {
  for (let x = 0; x < 512; x++) {
    for (let y = 0; y < 512; y++) {
      const base = new THREE.Color(0xffffff)
      const value = perlin.noise(x / 12, y / 10, 0) //产生噪音值
      base.multiplyScalar(value) //给Color的RGB每个分量都乘以给定值
      ctx.fillStyle = '#' + base.getHexString()
      ctx.fillRect(x, y, 1, 1)
    }
  }
}

生成的噪声图如下
在这里插入图片描述

2.3 创建凹凸贴图材质的网格对象

createMesh(geom) {
  const bumpMap = new THREE.Texture(this.canvas)//将canvas画布上的噪音图创建为纹理
  geom.computeVertexNormals()
  const mat = new THREE.MeshPhongMaterial({ color: 0x02ce50 })
  mat.bumpMap = bumpMap //将创建的纹理设置为材质的凹凸贴图
  bumpMap.needsUpdate = true
  const mesh = new THREE.Mesh(geom, mat)
  return mesh
}

2.4 更新bumpScale

 // 更新属性
 updateFun() {
   this.cube.rotation.y += 0.01
   this.cube.rotation.x += 0.01
   this.cube.material.bumpScale = this.properties.bumpScale.value //更新影响凹凸程度的bumpScale属性
   this.cube.material.bumpMap.needsUpdate = true //更新材质的凹凸贴图
 }

4. demo代码

<template>
  <div>
    <div id="container" />
    <div class="canvas-container">
      <div id="canvas-output" style="float:left" />
    </div>
    <div class="controls-box">
      <section>
        <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" />
              </el-col>
              <el-col :span="3">
                <span class="vertice-span">{{ item.value }}</span>
              </el-col>
            </div>
          </div>
        </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 {
      properties: {
        bumpScale: {
          name: 'bumpScale',
          value: 1,
          min: -2,
          max: 2,
          step: 0.1
        }
      },
      canvas: null,
      ratationSpeed: 0.01,
      cube: null,
      camera: null,
      scene: null,
      renderer: null,
      controls: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    formatTooltip(val) {
      return val
    },
    // 初始化
    async init() {
      await this.addCanvas()
      this.createScene() // 创建场景

      this.createLight() // 创建光源
      this.createCamera() // 创建相机
      this.createRender() // 创建渲染器

      this.createModels() // 创建模型
      this.createControls() // 创建控件对象
      this.render() // 渲染
    },
    addCanvas() {
      const publicPath = process.env.BASE_URL
      this.canvas = document.createElement('canvas')
      this.canvas.setAttribute('width', 256)
      this.canvas.setAttribute('height', 256)
      this.canvas.setAttribute(
        'style',
        'position: absolute; x:0; y:0; bottom: 0px'
      )
      document.getElementById('canvas-output').appendChild(this.canvas)

      const ctx = this.canvas.getContext('2d')
      const date = new Date()
      const pn = new Perlin('rnd' + date.getTime())

      this.fillWithPerlin(pn, ctx)
    },

    //对canvas噪音处理
    fillWithPerlin(perlin, ctx) {
      for (let x = 0; x < 512; x++) {
        for (let y = 0; y < 512; y++) {
          const base = new THREE.Color(0xffffff)
          const value = perlin.noise(x / 12, y / 10, 0) //产生噪音值
          base.multiplyScalar(value) //给Color的RGB每个分量都乘以给定值
          ctx.fillStyle = '#' + base.getHexString()
          ctx.fillRect(x, y, 1, 1)
        }
      }
    },
    // 创建场景
    createScene() {
      this.scene = new THREE.Scene()
    },

    // 创建模型
    createModels() {
      this.cube = this.createMesh(new THREE.BoxGeometry(10, 10, 10))
      this.cube.position.x = 2
      this.scene.add(this.cube)
    },

    createMesh(geom) {
      const bumpMap = new THREE.Texture(this.canvas) //将canvas画布上的噪音图创建为纹理
      geom.computeVertexNormals()
      const mat = new THREE.MeshPhongMaterial({ color: 0x02ce50 })
      mat.bumpMap = bumpMap //将创建的纹理设置为材质的凹凸贴图
      bumpMap.needsUpdate = true
      const mesh = new THREE.Mesh(geom, mat)
      return mesh
    },

    // 创建光源
    createLight() {
      // 环境光
      const ambientLight = new THREE.AmbientLight(0x141414) // 创建环境光
      this.scene.add(ambientLight) // 将环境光添加到场景

      const light = new THREE.DirectionalLight() // 创建平行光
      light.position.set(0, 30, 20)
      this.scene.add(light)
    },
    // 创建相机
    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(35, k, 0.1, 1000)

      this.camera.position.set(0, 12, 28) // 设置相机位置

      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()
      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)
    },

    // 更新属性
    updateFun() {
      this.cube.rotation.y += 0.01
      this.cube.rotation.x += 0.01
      this.cube.material.bumpScale = this.properties.bumpScale.value //更新影响凹凸程度的bumpScale属性
      this.cube.material.bumpMap.needsUpdate = true //更新材质的凹凸贴图
    },
    render() {
      this.updateFun()
      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;
}

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值