Add some texture to one side of the quadrilateral

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!

Answer №1

When working with a rectangle, I aim to have the right half of it colored red while the left half should display the complete image.

The assigned texture coordinates fall within the range [0.0, 1.0]. The midpoint of the texture sits at (0.5, 0.5). As a result, in the right section of the texture, the x-coordinate is greater than 0.5. For the left instance, you must increase the x coordinate by 2.0:

gl_FragColor = vUv.x > 0.5 
    ? vec4(1.0, 0.0, 0.0, 1.0) 
    : texture2D(texture, vec2(vUv.x*2.0, vUv.y));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Neglecting to utilize the document object within a React component results in the error "document is not defined."

I am utilizing browser detection code within a React component import React, { useState } from 'react' const BrowserDetectionComponent = ({props}) => { const isIE = document.documentMode; return ( <div> Custom browser s ...

Exploring the nesting of client components in Next.jsIf you are

Exploring the realm of NextJS and React, I find myself delving into the realm of client components. One such client component I'm working with is called Form.jsx. It looks something like this: export default function FormHome() { ... a plethora of ...

Modifying TextField color in a react application with Material UI

I have a react component that consists of a text field and a button. I want these elements to be displayed in green color on a black background, but I am unable to modify the default colors of all the elements. Following a similar query on how to change th ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...

Adjust the overall cost according to the quantity using jQuery or JavaScript

I'm currently working on a project that involves input fields for Product Price, Quantity Form Field, and displaying the Total price. My goal is to have the Total price automatically update based on the product price and quantity with jQuery. I am loo ...

Keep the user on the current page even after submitting the parameter

I have a situation where I am loading a page into a specific div. This loaded page contains a link that includes a parameter which directs to another page for deletion. However, when I click on the loaded page within the div, it redirects me to the deletio ...

Encountering issues with loading styles in Vue single file components

While working on my project at this link, I encountered an issue with displaying a styled modal. Despite trying to import the styles using: <style scoped> @import "../styles/modal-style.css"; </style> and even directly pasting the co ...

The Xero Node OAuth Authorize Callback URL is malfunctioning after granting access

When utilizing the xero-node library to produce a Request Token using the getRequestToken function, the URL provided does not automatically redirect the user to the designated callback address specified in the configuration. Instead, a screen displaying a ...

What is the best way to manage the 'content' attribute in TSX?

I'm currently developing an application that utilizes schema.org. In the code snippet below, you can see how I've implemented it: <span itemProp="priceCurrency" content="EUR">€</span> According to schema.org do ...

Exploring the world of npm packages: from publishing to utilizing them

Exploring My Module npmpublicrepo -- package.json -- test.js The contents of package.json are as follows: { "name": "npmpublicrepo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Erro ...

How would you utilize jQuery to access the "option" array of a select control with the attribute of multiple=true by utilizing the find() method?

When using jquery, I am attempting to access selected items from a select control that has multiple=true. My goal is to reference them by name criteria and then iterate through the list. Below is my current code snippet: var currentRow = $(this); // sele ...

Ways to insert a hyperlink within a div element

Consider the following HTML structure: <article id="1919"> <div class="entry-content clearfix"> <div></div> <div></div> </div> </article> &l ...

Ways to update a JSON object within an array of objects

I've got an array of objects // Extracted from the database $scope.users = [{"$id":"1","UserID":3,"Name":"A","Selected":false},{"$id":"2","UserID":4,"Name":"B","Selected":false},{"$id":"3","UserID":5,"Name":"C","Selected":false},{"$id":"4","UserID":6 ...

Error message: Issue with TypeScript and cleave.js - 'rawValue' property is not found on type 'EventTarget & HTMLInputElement'

I am encountering an error with the onChange event while implementing cleave in typescript. TypeScript is throwing an error indicating that 'rawValue' is not present in event.target. Here is my code: import React, { useCallback, useState, useEff ...

Using PHP in combination with Ajax for automatically performing an action when there is an update

My goal is to have the latest value entered in the database trigger the playing of a specific song. For instance, if someone on the other side of the world selects a song on their phone, that same song should automatically start playing on all devices with ...

Listener for clicking on a marker in Google Maps

Trying to add a click event to Google Map markers in my Cordova app has proven to be quite challenging. The recommended ways mentioned in the documentation don't seem to work, unless I make the marker draggable - which is not an option for me. It seem ...

Ways to create an object based on another object

Currently, I am teaching myself Javascript. My focus is on working with Vuejs and express for a CRUD App. In one of my components, I retrieve data from my backend using the API: localhost:3000/api/transport. The response contains all objects from the data ...

Halting Execution After Placing an Object in Three.js Scene with Javascript

It seems like a simple task, but I've been struggling with it for days. How can I add objects to a scene with a pause between each addition? Inside a loop{ I call the make_obj function() then I call the wait function() } The issue is that the pr ...

Is it possible to instantiate a Backbone view by referencing its string name that is stored within a JavaScript object?

I am currently working on a visual builder that utilizes different views for each component. Each view is defined as shown below: $(function() { var parallaxView = new Backbone.view.extend({ .... }); var parallaxView = new Backbone.view.e ...

Exploring the capabilities of the Next.js router and the useRouter

import { routeHandler } from "next/client"; import { useRouteNavigator } from "next/router"; const CustomComponent = () => { const routerFromHook = useRouteNavigator(); } export default CustomComponent; Can you explain the disti ...