无限变幻场景(Fluctuation)

无限变幻场景(Fluctuation)

示例

在这里插入图片描述

HTML

<!--
  Parametric surface with THREE.js
-->

<h1 class="kern">無限に</h1>
<a href="https://esmes.fi"><span class="kern tagline">esmes<sup>&copy;</sup></span></a>

CSS

html {
  background-color: #000;
  color: #fff;
  font-family: "Roboto", sans-serif;
  line-height: 1;
}
html,body {
  overflow: hidden;
}
a {
  color: currentColor;
  text-decoration: inherit;
  &:hover {
    text-decoration: underline;
  }
}
h1 {
  font-size: 25vmin;
  font-weight: 900;
  left: 50%;
  margin: 0;
  position: absolute;
  top: 31%;
  text-shadow: -.033em -.05em 0 hsl(270, 99%, 50%);
  transform: translate(-50%, -50%) skewX(-6deg) skewY(-6deg) ;
  white-space: nowrap;
  z-index: 1;
}
.tagline {
  bottom: -.25em;
  right: -.25em;
  display: block;
  font-size: 13px;
  font-weight: 300;
  padding: 1em;
  position: absolute;
  width: auto;
  white-space: nowrap;
  z-index: 1;
}
@supports (object-fit: cover) {
  canvas {
    position: absolute;
    left: 0;
    height: 100% !important;
    top: 0;
    width: 100% !important;
    object-fit: cover;
  }
}
canvas {
  image-rendering: pixelated;
}
.char1 {
  margin-right: -.025em;
}
.char2 {
  margin-right: -.1em;
}

JS

console.clear();

THREE.RGBShiftShader = {
	uniforms: {
		"tDiffuse": { value: null },
		"amount":   { value: 0.0025 },
		"angle":    { value: 90 }
	},
	vertexShader: [
		"varying vec2 vUv;",
		"void main() {",
			"vUv = uv;",
			"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
		"}"
	].join( "\n" ),
	fragmentShader: [
		"uniform sampler2D tDiffuse;",
		"uniform float amount;",
		"uniform float angle;",
		"varying vec2 vUv;",
		"void main() {",
			"vec2 offset = amount * vec2( cos(angle), sin(angle));",
			"vec4 cr = texture2D(tDiffuse, vUv + offset);",
			"vec4 cga = texture2D(tDiffuse, vUv);",
			"vec4 cb = texture2D(tDiffuse, vUv - offset);",
			"gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a);",
		"}"
	].join( "\n" )
};

function threeShaderFXAA (opt) {
  if (typeof window.THREE === 'undefined') {
    throw new TypeError('You must have THREE in global scope for this module.')
  }
  opt = opt || {}
  return {
    uniforms: {
      tDiffuse: { type: 't', value: new THREE.Texture() },
      resolution: { type: 'v2', value: opt.resolution || new THREE.Vector2() }
    },
    vertexShader: "#define GLSLIFY 1\nvarying vec2 vUv;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec2 resolution;\n\nvoid main() {\n  vUv = uv;\n  vec2 fragCoord = uv * resolution;\n  vec2 inverseVP = 1.0 / resolution.xy;\n  v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n  v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n  v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n  v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n  v_rgbM = vec2(fragCoord * inverseVP);\n\n  gl_Position = projectionMatrix *\n              modelViewMatrix *\n              vec4(position,1.0);\n}\n",
    fragmentShader: "#define GLSLIFY 1\nvarying vec2 vUv;\n\n//texcoords computed in vertex step\n//to avoid dependent texture reads\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\n//make sure to have a resolution uniform set to the screen size\nuniform vec2 resolution;\nuniform sampler2D tDiffuse;\n\n/**\nBasic FXAA implementation based on the code on geeks3d.com with the\nmodification that the texture2DLod stuff was removed since it's\nunsupported by WebGL.\n\n--\n\nFrom:\nhttps://github.com/mitsuhiko/webgl-meincraft\n\nCopyright (c) 2011 by Armin Ronacher.\n\nSome rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n\n    * Redistributions in binary form must reproduce the above\n      copyright notice, this list of conditions and the following\n      disclaimer in the documentation and/or other materials provided\n      with the distribution.\n\n    * The names of the contributors may not be used to endorse or\n      promote products derived from this software without specific\n      prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#ifndef FXAA_REDUCE_MIN\n    #define FXAA_REDUCE_MIN   (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n    #define FXAA_REDUCE_MUL   (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n    #define FXAA_SPAN_MAX     8.0\n#endif\n\n//optimized version for mobile, where dependent \n//texture reads can be a bottleneck\nvec4 fxaa_1540259130(sampler2D tex, vec2 fragCoord, vec2 resolution,\n            vec2 v_rgbNW, vec2 v_rgbNE, \n            vec2 v_rgbSW, vec2 v_rgbSE, \n            vec2 v_rgbM) {\n    vec4 color;\n    mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n    vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n    vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n    vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n    vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n    vec4 texColor = texture2D(tex, v_rgbM);\n    vec3 rgbM  = texColor.xyz;\n    vec3 luma = vec3(0.299, 0.587, 0.114);\n    float lumaNW = dot(rgbNW, luma);\n    float lumaNE = dot(rgbNE, luma);\n    float lumaSW = dot(rgbSW, luma);\n    float lumaSE = dot(rgbSE, luma);\n    float lumaM  = dot(rgbM,  luma);\n    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n    \n    mediump vec2 dir;\n    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n    \n    float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n                          (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n    \n    float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n    dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n              max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n              dir * rcpDirMin)) * inverseVP;\n    \n    vec3 rgbA = 0.5 * (\n        texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n        texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n    vec3 rgbB = rgbA * 0.5 + 0.25 * (\n        texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n        texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n    float lumaB = dot(rgbB, luma);\n    if ((lumaB < lumaMin) || (lumaB > lumaMax))\n        color = vec4(rgbA, texColor.a);\n    else\n        color = vec4(rgbB, texColor.a);\n    return color;\n}\n\nvoid main() {\n  vec2 fragCoord = vUv * resolution;   \n  gl_FragColor = fxaa_1540259130(tDiffuse, fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"
  }
}

(function doit() {
  var ADAPTIVE_RESOLUTION = false;
  var UMAX = 64;
  var VMAX = 32;
  var SMOOTH = false;
  var SPEED = 1.156845;
  
  var scene = new THREE.Scene();
  var webGLRenderer = new THREE.WebGLRenderer({
    antialias: true
  });
  webGLRenderer.setClearColor(
    new THREE.Color(0x111111)
  );
  function resize(dotSize) {
    console.info("Resolution "+ (1/dotSize*100).toFixed(0) + "%");
    webGLRenderer.setSize(
      window.innerWidth / dotSize,
      window.innerHeight / dotSize
    );
  }
  resize(1);
  
  document.body.appendChild(webGLRenderer.domElement);
  function getVFoV(adjust) {
    return window.innerHeight / window.innerWidth * (3 * adjust);
  }
  var camera = new THREE.PerspectiveCamera(
    getVFoV(1), // fov
    window.innerWidth / window.innerHeight, // aspect
    1, 1000 // near, far
  );

  camera.position.x = 0;
  camera.position.y = 256;
  camera.position.z = 256;
  camera.lookAt(
    new THREE.Vector3(10, 0, 0)
  );
  function randomLightColor() {
    var lightColors = [
      0xff4422,
      0x22aaff,
      0x44ff66,
      0x66ff44,
      0xff2244,
      0xaa22ff
    ];
    var randomIndex = Math.floor(
      lightColors.length * Math.random()
    );
    var textElement = document.querySelector("h1");
    var color = "#" + lightColors[randomIndex].toString(16);
    var shadowStyle = window.getComputedStyle(textElement)["text-shadow"];
    var tail = "";
    try {
      if (shadowStyle.indexOf("rgb(") >= 0) {
        tail = shadowStyle.split(")")[1];
        textElement.style.textShadow = color + tail;
      }
    } catch(e) {
      console.warn(e);
    }
    return new THREE.Color(lightColors[randomIndex]);
  }
  
  var RLight = new THREE.DirectionalLight(
    0xff4422, 1.125
  );
  RLight.position.x = 33;
  RLight.position.y = 25;
  RLight.position.z = -25;
  RLight.lookAt(new THREE.Vector3(0,0,0));
    
  var LLight = new THREE.DirectionalLight(
    0x22aaff, 1.125
  );
  LLight.position.x = -33;
  LLight.position.y = 25;
  LLight.position.z = -25;
  LLight.lookAt(new THREE.Vector3(0,0,0));
  
  scene.add(LLight);

  scene.add(RLight);
  
  var circle = function(u,v) {
    var r = 27.75;
    var x = Math.sin(u) * Math.cos(v * Math.PI * 2) * r;
    var y = 0;
    var z = -Math.sin(u) * Math.sin(v * Math.PI * 2) * r;
    return new THREE.Vector3(x,y,z);
  };
  function createMesh(geom) {
    geom.applyMatrix(new THREE.Matrix4().makeTranslation(0, 0, 0));
    var meshMaterial = new THREE.MeshPhongMaterial({
      specular: 0xffffff,
      color: 0x000000,
      shininess: 33,
      wireframe: false,
      shading: SMOOTH ? THREE.SmoothShading : THREE.FlatShading
    });
    //meshMaterial.side = THREE.DoubleSide;
    geom.mergeVertices();
    var plane = THREE.SceneUtils.createMultiMaterialObject(geom, [meshMaterial]);
    return plane;
  }
  var mesh = createMesh(new THREE.ParametricGeometry(circle, UMAX, VMAX));

  scene.add(mesh);

  function wiggleGeo(g, t) {
    g.vertices = g.vertices.map(createWiggleVertsMap(t));
    g.verticesNeedUpdate = true;
    if(SMOOTH) g.computeFaceNormals();
    g.computeVertexNormals();
    return g;
  }
  
  var createWiggleVertsMap = function(time) {
    var intensity = Math.sin(time / 5000) / 2 + .75;
    var ti = -time / 1000 * SPEED;

    return function wiggleVerts(vert, index, arr, time) {
      var u = (index / UMAX) % 1;
      var v = ((index-1) % UMAX) / UMAX;
      vert.y =
        (
          intensity * Math.sin(ti + u * Math.PI * (UMAX/2.84618))
        ) * ((1-v)*.85)
         //+ (Math.random() / (1.66-u-v) * 0.0006125); // noisy edge
        ;
      return vert;
    };
  }
  
  var composer = new THREE.EffectComposer( webGLRenderer );
  var renderPass = new THREE.RenderPass( scene, camera );
  
  var copyShader = new THREE.ShaderPass(THREE.CopyShader);
  copyShader.renderToScreen = true;
  
  var glitchPass = new THREE.GlitchPass(
    Math.max(window.innerWidth, window.innerHeight)
  );
  glitchPass.generateTrigger= function() {
		this.randX=Math.random()*100+100>>0;
	};
  glitchPass.enabled = false;
  glitchPass.uniforms.col_s.value = 1/8;

  console.log(glitchPass);
  
  var rgbShiftPass = new THREE.ShaderPass(THREE.RGBShiftShader);
  rgbShiftPass.uniforms.amount.value = 0.0042;
  
  var bloomPass = new THREE.UnrealBloomPass(
    new THREE.Vector2(window.innerWidth, window.innerHeight),
    .5, 1.1, 0.666 // strength, radius, threshold
  );
  
  var fxaa = new THREE.ShaderPass(threeShaderFXAA());
  fxaa.uniforms.resolution.value.set(window.innerWidth, window.innerHeight)
  
  composer.addPass(renderPass);
  composer.addPass(rgbShiftPass);
  composer.addPass(bloomPass);
  composer.addPass(glitchPass);
  composer.addPass(fxaa);
  composer.addPass(copyShader);
 
  var frameIndex = 0;
  var lastTime = 0;
  var rd = Array(3).fill(0);
  
  render(0);
  function render(t) {
    frameIndex++;
    if(ADAPTIVE_RESOLUTION) {
      var dt = t-lastTime;
      if(dt <= 20) {
        rd[0]++;
      } else if(dt < 40) {
        rd[1]++;
      } else {
        rd[2]++;
      }
      if(frameIndex % 100 === 0) {
        resize(
          rd.reduce(getMaxValueIndex, 0) + 1
        );
        rd = rd.fill(0);
      }
    }
    lastTime = t;
    var oldFoV = camera.fov;
    if(frameIndex % 250 === 0) {
      RLight.color = randomLightColor();
      LLight.color = randomLightColor();
      camera.fov = getVFoV(0.0236125);
      glitchPass.enabled = true;
    }
    if (frameIndex % 233 === 0) {
      camera.fov = getVFoV(1);
      glitchPass.enabled = false;
    }
    if(camera.fov !== oldFoV) {
      camera.updateProjectionMatrix();
    }
    if(frameIndex >= Number.MAX_SAFE_INTEGER) {
      frameIndex = 0;
    }
    mesh.children[0].geometry = wiggleGeo(mesh.children[0].geometry, t);
    mesh.rotation.y += Math.PI / 180 / 30;
    requestAnimationFrame(render);
    composer.render(scene, camera);
  }
  

  var tanFOV = Math.tan( ( ( Math.PI / 180 ) * camera.fov / 2 ) );
  var windowHeight = window.innerHeight;
  function onWindowResize( event ) {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.fov = ( 360 / Math.PI ) * Math.atan( tanFOV * ( window.innerHeight / windowHeight ) );
    camera.updateProjectionMatrix();
    camera.lookAt( scene.position );
    webGLRenderer.setSize( window.innerWidth, window.innerHeight );
    composer.setSize( window.innerWidth, window.innerHeight );
  }
 // window.addEventListener( 'resize', onWindowResize, false );
  
  Array.from(document.querySelectorAll(".kern")).forEach(charming);
  
})();

function getMaxValueIndex (a, v, i, ar){
  return v > a ? i : a;
}
发布了114 篇原创文章 · 获赞 54 · 访问量 8536

猜你喜欢

转载自blog.csdn.net/weixin_45544796/article/details/104178428