three.js

Three.js Rotate Texture


I have a texture applied to a mesh I can change the offset with

mesh.material.map.offset.set

I can change the scaling with

mesh.material.repeat.set

so my question is, how can I rotate texture inside a plane?

Example:

From This:

enter image description here

To this

enter image description here

Thanks.


Solution

  • You will need to use a 2D canvas as a texture for this:

    const width = window.innerWidth;
    const height = window.innerHeight;
    
    const scene = new THREE.Scene();
    
    const camera = new THREE.PerspectiveCamera(30, width / height, 1, 1000);
    camera.position.z = 100;
    
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);
    document.body.appendChild(renderer.domElement);
    
    const img = new Image();
    img.onload = createMeshThenRender;
    img.src = 'img.jpg';
    
    function createMeshThenRender() {
        const imgWidth = 256;
        const imgHeight = 256;
        const mapCanvas = document.createElement('canvas');
        mapCanvas.width = mapCanvas.height = 256;
    
        // document.body.appendChild( mapCanvas );
        const ctx = mapCanvas.getContext('2d');
        ctx.translate(imgWidth / 2, imgHeight / 2);
        ctx.rotate(Math.PI / 4);
        ctx.translate(-imgWidth / 2, -imgHeight / 2);
        ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
    
        const texture = new THREE.Texture(mapCanvas);
        texture.needsUpdate = true;
    
        mesh = new THREE.Mesh(
            new THREE.PlaneGeometry(50, 50, 1, 1),
            new THREE.MeshBasicMaterial({
                map: texture
            })
        );
        scene.add(mesh);
        renderer.render(scene, camera);
    }