I have a project in threejs where I need to display an image of a cat within a rectangle.
The challenge is to render the right half of the rectangle in red, while displaying the full stretched image of the cat on the left half. Here's my current scene setup:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 2;
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BufferGeometry();
var imageSize = {width: 3, height: 2};
// add verts
var coords = {x: -1.5, y: -1, z: 0};
var vertices = new Float32Array([
coords.x, coords.y, coords.z,
coords.x+imageSize.width, coords.y, coords.z,
coords.x+imageSize.width, coords.y+imageSize.height, coords.z,
coords.x, coords.y+imageSize.height, coords.z,
])
var uvs = new Float32Array([
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
])
geometry.setIndex([0,1,2, 2,3,0])
geometry.setAttribute('position', new THREE.BufferAttribute( vertices, 3 ));
geometry.setAttribute('uv', new THREE.BufferAttribute( uvs, 2) )
var loader = new THREE.TextureLoader();
var url = 'https://s3.amazonaws.com/duhaime/blog/tsne-webgl/assets/cat.jpg';
var material = new THREE.RawShaderMaterial({
uniforms: {
texture: {
type: 't',
value: loader.load(url)
},
},
vertexShader: document.getElementById('vertex-shader').textContent,
fragmentShader: document.getElementById('fragment-shader').textContent
});
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0,0,0)
scene.add(mesh);
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
console.clear();
};
render();
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js'></script>
<script type='x-shader/x-vertex' id='vertex-shader'>
precision mediump float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 cameraPosition;
attribute vec3 position;
attribute vec3 translation;
attribute vec2 uv;
varying vec2 vUv;
varying vec3 vPosition;
void main() {
vUv = uv;
vPosition = position;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
</script>
<script type='x-shader/x-fragment' id='fragment-shader'>
precision highp float;
uniform sampler2D texture;
varying vec2 vUv;
varying vec3 vPosition;
void main() {
vec2 uv = vUv;
if (vPosition.x > 0.0) {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
} else {
gl_FragColor = texture2D(texture, uv);
}
}
</script>
Currently, only half of the cat image is showing on the left side of the rectangle. I'm seeking guidance on how to display the full cat image properly. Any insights or suggestions would be highly appreciated!