简体   繁体   中英

How to place a texture in a specific location?

In my code, I'm mixing two textures. I want to position a texture at any place on the plane but when I add an offset to the texture UV XY coordinate the image just gets stretched.

offsetText1 = vec2(0.1,0.1);       
vec4 displacement  = texture2D(utexture1,vUv+offsetText1);

How do I move the texture to any position without stretching it?

VERTEX SHADER:

  
  varying vec2 vUv;
  uniform sampler2D utexture1;
  uniform sampler2D utexture2;
  varying vec2 offsetText1;

  void main() {
      offsetText1 = vec2(0.1,0.1);
      vUv = uv;
      vec4 modelPosition = modelMatrix * vec4(position, 1.0);
      vec4 displacement  = texture2D(utexture1,vUv+offsetText1);
      vec4 displacement2 = texture2D(utexture2,vUv);
      modelPosition.z   += displacement.r*1.0;
      modelPosition.z   += displacement2.r*40.0;
      gl_Position       = projectionMatrix * viewMatrix * modelPosition;
  }
  

FRAGMENT SHADER:

  #ifdef GL_ES
  precision highp float;
  #endif
  uniform sampler2D utexture1;
  uniform sampler2D utexture2;
  varying vec2 vUv;
  varying vec2 offsetText1;

  void main() {
      vec3 c;
      vec4 Ca = texture2D(utexture1,vUv+offsetText1 );
      vec4 Cb = texture2D(utexture2,vUv);
      c       = Ca.rgb * Ca.a + Cb.rgb * Cb.a * (2.0 - Ca.a);
      gl_FragColor = vec4(c, 1.0);
  }
  

image with offsetText1 = vec2(0.0,0.0); no stretching

image with offsetText1 = vec2(0.1,0.1); image is being stretched from the top right corner. stretching

That's the behavior of textures. They extend in the range from [0, 1] , so when you go beyond 1 or below 0, they'll "wrap". You need to tell it what to do when wrapping. Do you want it to repeat, stretch, or mirror?

You could establish this with the texture.wrapS and .wrapT properties , which accepts one of 3 values:

THREE.RepeatWrapping
THREE.ClampToEdgeWrapping
THREE.MirroredRepeatWrapping

If you want to just show white where the texture extends out of bounds, then you'd have to do that programmatically in your shader code. Here's some pseudocode:

if (uv < 0 || > 1)
   color = white

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM