Fit text into mesh

Hello.

I have a rect mesh and text . text content (the length) is dynamic. If text is overflow out of rect. I need to hide this part and only show the part in rect.

I searched a lot. But I couldn’t find slution

you’ll be able to use three-bvh-csg for this, using the “intersection” operator i believe, this would dynamically clip anything outside the bounds of your rect… otherwise you could look into the usage of a clippingPlane for each side of your rect…

drei/text is based on troika-sdf-text and it has masking options, you can define a rect. if that’s too complicated just mask it yourself, you can either use stencil (drei/stencil) or drei/meshportalmaterial, which is probably the easiest. these two allow you to mask anything btw, text, meshes, whatever you throw at it.

        <mesh>
          <planeGeometry args={[6, 2]} />
          <MeshPortalMaterial transparent worldUnits blur={0.2}>
              <Text>CSS is awesome</Text>
          </MeshPortalMaterial>
        </mesh>

in my case, I can’t use react-fibre. I need to implement it in threejs

could you please make the second solution a little more clear. I couldn’t get what the point you meant.

Sorry I read this as “I have a react mesh” :smile:

all the solutions do apply to you, though. if you use sdf text (troika), then you can clip-rect it. see troika/packages/troika-three-text at main · protectwise/troika · GitHub i don’t know what kind of text you use but troika is very good.

you can use stencil Inverted stencil buffer - CodeSandbox

the mesh that creates the mask just needs this on the material, it’s a regular mesh, for instance a planeGeometry:

    stencilWrite: true,
    stencilRef: 1,
    stencilFunc: inverse ? THREE.NotEqualStencilFunc : THREE.EqualStencilFunc,
    stencilFail: THREE.KeepStencilOp,
    stencilZFail: THREE.KeepStencilOp,
    stencilZPass: THREE.KeepStencilOp,

and the objects that you want to mask with that mesh above need this:

        colorWrite: false,
        depthWrite: false,
        stencilWrite: true,
        stencilRef: 1,
        stencilFunc: THREE.AlwaysStencilFunc,
        stencilFail: THREE.ReplaceStencilOp,
        stencilZFail: THREE.ReplaceStencilOp,
        stencilZPass: THREE.ReplaceStencilOp,

and the last option is shader masking pmndrs assets (forked) - CodeSandbox

for this you render the masked contents into a webglrendertarget with a shader that renders screen space, not uv projected. now you only need to put that texture onto any shape and it will become the mask.