THREE.js repeat wrapping texture in shader

2019-03-31 06:59发布

I want to repeat wrapping texture in THREE.js shader.

The original texture image is:

enter image description here

I want it to repeat 4x4 times which will looks like:

enter image description here

But with the following code, it turns out to be:

enter image description here

Vertex shader:

varying vec2 vUv;

uniform float textRepeat;

void main()
{    
    // passing texture to fragment shader
    vUv = uv * textRepeat;

    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

Fragment shader:

varying vec2 vUv;

uniform sampler2D texture;

void main() {
    // add origianl texture
    gl_FragColor = texture2D(texture, vUv);
}

uniforms in a JavaScript file, in which textureRepeat gives the times need to be repeated:

uniforms: {
    texture: {
        type: 't', 
        value: THREE.ImageUtils.loadTexture('image/box.jpg')
    },
    textRepeat: {
        type: 'f',
        value: 8
    }
}

Could anyone tell me what's going wrong here?

2条回答
趁早两清
2楼-- · 2019-03-31 07:11

By default, textures have "Clamp To Edge" wrapping mode, which means u or v over 1 will still be 1 instead of wrapping back to 0.

To fix this, you need to set the wrapping mode of your texture to "Repeat", which happens like this:

uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping

查看更多
淡お忘
3楼-- · 2019-03-31 07:17

One additional trick could be to do something like fract(uv) and get the fractional portion. (it would always be within 0-1)

查看更多
登录 后发表回答