Дисплейсмент за мышкой
2 картинки, twgl.js и m3.js
by vovkasolovev
HTML
<script src="https://webglfundamentals.org/webgl/resources/m3.js"></script>
<script src="https://cdn.jsdelivr.net/gh/greggman/twgl.js@master/dist/4.x/twgl-full.min.js"></script>
<canvas id="displacement" class="displace" data-displace-img="https://i.imgur.com/xKYRSwu.jpg" data-displace-map="https://i.imgur.com/W9QazjL.jpg" data-displace-speed="5"></canvas>
CSS
body { margin: 0;}
canvas { width: 100vw; height: 100vh; display: block; }
JavaScript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
const canvas = document.getElementById("displacement");
const gl = canvas.getContext("webgl");
if (!gl) {
return;
}
let originalImage = { width: 1, height: 1 }; // replaced after loading
const originalTexture = twgl.createTexture(gl, {
src: "https://i.imgur.com/xKYRSwu.jpg",
crossOrigin: '',
}, (err, texture, source) => {
originalImage = source;
});
const mapTexture = twgl.createTexture(gl, {
src: "https://i.imgur.com/W9QazjL.jpg", crossOrigin: '',
});
// compile shaders, link program, lookup location
//const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);
const shaders = {
vs : `attribute vec2 position;
attribute vec2 texcoord;
uniform mat3 u_matrix;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(u_matrix * vec3(position, 1), 1);
v_texcoord = texcoord;
}`,
fs : `precision mediump float;
uniform vec2 u_mouse;
uniform sampler2D u_originalImage;
uniform sampler2D u_mapImage;
varying vec2 v_texcoord;
void main() {
vec4 depthDistortion = texture2D(u_mapImage, v_texcoord);
float parallaxMult = depthDistortion.r;
vec2 parallax = (u_mouse) * parallaxMult;
vec4 original = texture2D(u_originalImage, (v_texcoord + parallax));
gl_FragColor = original;
}`
}
const programInfo = twgl.createProgramInfo(gl, [shaders.vs, shaders.fs]);
// calls gl.createBuffer, gl.bindBuffer, gl.bufferData for a quad
const bufferInfo = twgl.primitives.createXYQuadBufferInfo(gl);
const mouse = [0, 0];
document.addEventListener('mousemove', (event) => {
mouse[0] = (event.clientX / gl.canvas.clientWidth * 2 - 1) * -0.01 * 5;
mouse[1] = (event.clientY / gl.canvas.clientHeight * 2 - 1) * -0.01 * 5;
});
document.addEventListener('touchmove', (event) => {
mouse[0] = (event.touches[0].clientX / gl.canvas.clientWidth * 2 - 1) * -0.01 * 5;
mouse[1] = (event.touches[0].clientY /...