实现原理
利用three.js根据深度图来控制不同深度位置像素位移距离不同,营造3D效果。
前期准备
深度图生成网站 LeiaPix Converter
注册登录完成后
第一步点击upload上传你的图片(建议不要上传带有人物或者较为模糊的图片,不然效果可能会造成人物变形)
第二步点击分享选择深度图下载
第三步在你的项目中引入three.js(各个框架不同,这里以静态页为例)
下载three.js 并引入项目
three.js github Releases · mrdoob/three.js (github.com) (这里我下载的最新版)
准备好这些后就可以开始激情撸代码了
<script>
const scene = new THREE.Scene();
/*相机*/ const camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.set(0, 0, 6);
/*渲染器*/ let renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);//向body内添加
/*加载纹理*/ const textureLoader = new THREE.TextureLoader(); const texture = textureLoader.load('/images/3d_img.jpg');//加载图片本身 const dapthTexture = textureLoader.load('/images/3dimg.jpg');//加载深度图
/*鼠标坐标2维向量*/ const mouse = new THREE.Vector2();
/*创建平面*/ const geometry = new THREE.PlaneGeometry(16, 9);
/*着色器材质*/ const material = new THREE.ShaderMaterial({ uniforms: { uTexture: { value: texture }, uDepthTexture: { value: dapthTexture }, uMouse: { value: mouse }, }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); } `, fragmentShader: ` uniform sampler2D uTexture; uniform sampler2D uDepthTexture; uniform vec2 uMouse; varying vec2 vUv; void main() { vec4 color = texture2D(uTexture, vUv); vec4 depth = texture2D(uDepthTexture, vUv); float depthValue = depth.r; float x = vUv.x + uMouse.x*0.01*depthValue; float y = vUv.y + uMouse.y*0.01*depthValue; vec4 newColor = texture2D(uTexture,vec2(x,y)); gl_FragColor = newColor; } `, });
const plane = new THREE.Mesh(geometry, material); scene.add(plane);
/*渲染*/ requestAnimationFrame(function animate() { material.uniforms.uMouse.value = mouse; requestAnimationFrame(animate); renderer.render(scene, camera); });
/*监听鼠标计算位移量*/ window.addEventListener('mousemove', (event) => { mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = (event.clientY / window.innerHeight) * 2 - 1; }) </script>
自此就可以看到效果了
标签:深度图,const,ai,THREE,vUv,window,new,3D From: https://www.cnblogs.com/yilei-zero/p/17202424.html