How to do 2D pixel displacement on a texture

how do you use 2D pixel displacement on a texture in three.js? this website shows what I mean well. not the 3D mapping or I would use a displacement map on my plane, but the 2D vertion.

You’ll have use shader materials for that, check out three js shader materials, you can look at some basic tutorials on youtube for this kinda effects.

Maybe you can use something like this as a start: Edit fiddle - JSFiddle - Code Playground

A shader material is not mandatory, you can also enhance a built-in material with custom code via Material.onBeforeCompile() like in the fiddle.

2 Likes

BTW: The described pixel displacement in the reference only works if repeat wrapping is used. Otherwise the texture coordinates are translated such that artifacts appear starting from the borders. That happens because the texture is sampled at a coordinate where no proper texel data can be fetched.

1 Like

it seems to be working, ish not quite though when I try that it makes marks on the map but doesn’t distort the map.


`
const flagc=this.getObjectByName(‘Flag’)
const loader = new THREE.TextureLoader();
const displacementMap = loader.load(‘https://i.imgur.com/dHLcm3j.png’);
displacementMap.format = THREE.LuminanceFormat;
flagc.material.onBeforeCompile= function(shader) {

shader.uniforms.displacementMap = {
  value: displacementMap
};

shader.fragmentShader = 'uniform sampler2D displacementMap;\n' + shader.fragmentShader;
shader.fragmentShader = shader.fragmentShader.replace(
  '#include <map_fragment>',
  `
 #ifdef USE_MAP
 
 		float displacement = texture2D( displacementMap, vUv ).r;

    vec4 texelColor = texture2D( map, vUv + displacement );
    
    texelColor = mapTexelToLinear( texelColor );
    diffuseColor *= texelColor;

  #endif
 `
);
flagc.material.userData.shader = shader;

};

is this correct or is there an error?

I figured out the issue the shader is only applying to the map I need it to apply to the emissive map, how would I change the shader to do that?

nm got it working