Texture Animation (r78+)

by jmcjc5u

HTML

<div id="info">non-square quad
  <br> GLSL Solution
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js">
</script>
<script id='myVertexShader' type="x-shader/x-vertex">
  varying vec4 textureCoord; 
  void main() { 

		textureCoord = vec4( 2.0*uv, 0.0, 1.0); 
    if (uv.y != 0.0) { 
    	textureCoord.w *= (uv.y); 
    } 
    gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); 
  } 
</script>
<script id='myFragmentShader' type="x-shader/x-vertex">
  uniform sampler2D uSampler; 
  varying vec4 textureCoord; 
  void main() { 
     gl_FragColor = texture2D(uSampler, vec2(textureCoord.x/textureCoord.w, textureCoord.y/textureCoord.w)); 
  }
</script>

CSS

#info {
  position: absolute;
  top: 0px;
  width: 100%;
  padding: 10px;
  text-align: center;
  color: #ffff00
}

body {
  overflow: hidden;
}

JavaScript

var camera, scene, renderer;
var controls;

init();
animate();

// reference:
// https://stackoverflow.com/questions/20661941/how-to-map-texture-on-a-custom-non-square-quad-in-three-js
//
function buildMesh() {

  var planeGeom = new THREE.Geometry();
  planeGeom.vertices.push(new THREE.Vector3(-15, -15, 0));
  planeGeom.vertices.push(new THREE.Vector3(15, -15, 0));
  planeGeom.vertices.push(new THREE.Vector3(5, 15, 0));
  planeGeom.vertices.push(new THREE.Vector3(-5, 15, 0));

	planeGeom.faces.push(new THREE.Face3(0, 1, 3));
  planeGeom.faces.push(new THREE.Face3(1, 2, 3));

  //Compute widths ratio
  var topWidth = 10; //Math.abs(Plane.TR.x - Plane.TL.x);
  var bottomWidth = 30; //Math.abs(Plane.BR.x - Plane.BL.x);
  var ratio = topWidth / bottomWidth;

  //create UV's  as barely explained in the link above (www.xyzw.us)
  var UVS = [
    new THREE.Vector2(0, 0),
    new THREE.Vector2(1, 0),
    new THREE.Vector2(ratio, ratio),
    new THREE.Vector2(0, ratio)
  ];

  //faceVertexUvs[materialID] [face index] [vertex index among face]
  planeGeom.faceVertexUvs[0][0] = [UVS[0], UVS[1], UVS[3]];
  planeGeom.faceVertexUvs[0][1] = [UVS[1], UVS[2], UVS[3]];
  //load the image
  var loader = new THREE.TextureLoader();
  loader.crossOrigin = ''
  var checkerTexture = loader.load('https://i.imgur.com/p8CRm9W.jpg');

  // wrapS/T works with shaders
  checkerTexture.wrapS = THREE.WrapRepeating
  checkerTexture.wrapT = THREE.WrapRepeating

  //checkerTexture.repeat.set (12,12)
  // texture matrix does not work in shaders

  //Now create custom shader parts
  customUniforms = {
    uSampler: {
      type: "t",
      value: checkerTexture
    },
  };

  var customMaterial = new THREE.ShaderMaterial({
    uniforms: customUniforms,
    vertexShader: document.getElementById('myVertexShader').textContent,
    fragmentShader: document.getElementById('myFragmentShader').textContent,
    side: THREE.DoubleSide
  });


  //create the mesh with the custom geometry and material
  var...