编译ThreeJS
我们将ThreeJS的源码从github上面download下来,然后进行编译之后,我们就能够得到一份最小的three.min.js的文件。用来给我们的GLSL项目使用
实现效果
我们想做到这样一个效果,当我们鼠标移动的时候,我们想改变renderer.domElement的背景颜色,让其随着我们的鼠标移动而改变背景颜色。
代码实现
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>glsl-template-02</title>
</head>
<body>
<script src="../libs/three.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
const vertexShaderSource=`
void main(){
gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);
}
`
const fragmentShaderSource=`
uniform vec3 u_color;
uniform vec2 u_mouse;
uniform vec2 u_resolution;
void main(){
vec3 color=vec3(u_mouse.x/u_resolution.x,0.0,u_mouse.y/u_resolution.y);
gl_FragColor =vec4(color,1.0);
}
`
const scene=new THREE.Scene()
const camera=new THREE.OrthographicCamera(-1,1,1,-1,0.1,10)
const renderer=new THREE.WebGLRenderer();
const uniforms = {
u_color: {value: new THREE.Color(0xff0000ff)},
u_mouse:{value:{x:0.0,y:0.0}},
u_resolution: {value: {x:0.0,y:0.0}}
}
const geometry=new THREE.PlaneGeometry(2,2)
const material=new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: vertexShaderSource,
fragmentShader: fragmentShaderSource
})
const plane = new THREE.Mesh(geometry,material)
scene.add(plane)
camera.position.z =1
renderer.setSize(window.innerWidth,window.innerHeight)
document.body.appendChild(renderer.domElement);
animate()
if('ontouchstart' in window){
document.addEventListener('touchmove',move)
}else{
window.addEventListener('resize',onWindowResize,false)
document.addEventListener('mousemove',move)
}
function move(evt){
uniforms.u_mouse.value.x=(evt.touches)?evt.touches[0].clientX:evt.clientX;
uniforms.u_mouse.value.y=(evt.touches)?evt.touches[0].clientY:evt.clientY;
}
onWindowResize()
function onWindowResize( event ) {
const aspectRatio = window.innerWidth/window.innerHeight;
let width, height;
if (aspectRatio>=1){
width = 1;
height = (window.innerHeight/window.innerWidth) * width;
}else{
width = aspectRatio;
height = 1;
}
camera.left = -width;
camera.right = width;
camera.top = height;
camera.bottom = -height;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
uniforms.u_resolution.value.x = window.innerWidth;
uniforms.u_resolution.value.y = window.innerHeight;
}
function animate(){
requestAnimationFrame(animate)
renderer.render(scene,camera)
}