Create a more custom appearance in THREEjs by cropping the texture instead of simply stretching it to

Currently in the process of developing an art-making app that focuses on image-based content using three.js.

Utilizing React.js for this project, but aiming to make the following explanations clear even for individuals unfamiliar with React. Within the component, a canvas is rendered and receives a locally-hosted image URL from a parent component.

The existing code is structured to generate a full-window canvas, form a 2D shape covering the entire canvas, and apply the provided image as a texture:

import React, { PureComponent } from 'react';
import * as THREE from 'three';

const textureLoader = new THREE.TextureLoader();

// Code snippets omitted for brevity

class Canvas extends PureComponent {
  // Code snippet omitted for brevity
  
  componentDidMount() {
    // Code snippet omitted for brevity
    
    // Initializing renderer, camera, scene, loading initial texture, etc.
    
    this.animate();
  }

  animate = () => {
    requestAnimationFrame(this.animate);

    this.renderer.render(this.scene, this.camera);
  }

  render() {
    return (
      <canvas innerRef={elem => this.canvas = elem} />
    );
  }
}

export default Canvas;

Encountering challenges where the texture appears stretched when displayed on the canvas. This results in distortion if the image dimensions do not match the window size precisely:

https://i.sstatic.net/clgI2.jpg

Seeking a solution similar to utilizing background-size: cover. The goal is to resize the image to fit the larger window dimension (e.g., 1000x1000) and then crop it at the center to display only the central 500px of height.

Answer №1

To provide a solution, it is essential to know the type of camera being used - whether it is a PerspectiveCamera, an OrthographicCamera, or a placeholder Camera. Additionally, if a custom shader is in use, understanding how vertex positions are calculated (utilizing properties like projectionMatrix) is crucial for effective troubleshooting.

For demonstration purposes, here is a simple implementation using an OrthographicCamera with an identity matrix and a 2-unit PlaneGeometry.

Assuming no other adjustments are made, this setup will display a plane filling the canvas. Subsequently, scaling adjustments are made considering both the canvas aspect ratio and image aspect ratio.

 // Code snippet 

// More code snippets
// Additional CSS snippet
// External script reference

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

What is the best way to determine if a JSON response value contains a hyphen '-' in Java Script?

When I receive a JSON response, I sometimes encounter values with hyphens. In JavaScript, the hyphen '-' is treated as a subtraction operator. JSON books": { "red": "2008-17801", "blue": "TERTERIAN-HAYK" } After obtaining these values, I store ...

What is the best way to compress a set of string data in AngularJS?

My coding attempt resulted in an error. Here is the code snippet: var UglifyJS = require("uglify-js"); var result = UglifyJS.minify("Hello world @123;", { fromString: true }); console.log(result.code); When using UglifyJs in the above code, I encountered ...

Is there a solution to rectify the error related to POST net::ERR_CONNECTION_REFUSED?

Every time I try to post via ajax, an error keeps popping up. Here are the snippets of my code: let xhr = new XMLHttpRequest() let data ={ "name": "test", "phone": "12345678", "email": &qu ...

Can someone please tell me how to convert this JavaScript regular expression into PHP code?

I created a JavaScript regular expression (regexp) and now I need it converted to PHP code: var alphaExp = /^[a-zA-ZåäöÅÄÖ\s\-]+$/; if (!fld.value.match(alphaExp)) { //ERROR OUTPUT HERE } Can someone provide me with the equivalent PHP c ...

AJAX - Icon-only picture upload feature inspired by Facebook's design

I need help with my picture upload system. I want to create a feature where users can click an icon, open Windows Explorer, select a picture, and have it automatically start uploading. However, every time I try to run this code using AJAX, I keep getting a ...

Errors slipping through the cracks of Express middleware

When it comes to using express and typescript, I am attempting to create a middleware for error handling similar to Sentry. Below is the code snippet: const catchError = ( error: Error, req: Request, _res: Response, next: any ) => { console. ...

implement express.bodyParser() alongside passport.js

Currently, I am developing a node server utilizing express.js and passport.js. I have encountered a situation where I need to avoid using the express.bodyParser() prior to app.use(passport.initialize()) and app.use(passport.session()). When I include app.u ...

When using a v-for within a v-if condition, the v-else directive does not function properly, resulting

Utilizing the Vue programming language and Element-ui framework, my code functions in a way where if an object contains something, it will be displayed. Otherwise, the menu button is disabled. The expected output should look like: a, b(disable), c, d, e ...

Tips for sending a multipart/form-data request using AJAX

I am facing an issue with the function below. I need to upload multiple files and submit a request via ajax. The content type is currently set as "text/plain;charset=UTF-8" but I want to change it to "multipart/form-data". Can anyone provide suggestions ...

Race Chart in AngularJS

My JSON file contains timestamps in the format hh:mm:ss.xx for different laps. Here is a sample of the data: [{"time":"00:05:52.92"},{"time":"00:06:22.26"},{"time":"00:06:22.26"},{"time":"00:02:22.26"},{"time":"00:07:22.26"},{"time":"00:06:22.26"},{"time" ...

Proper method for incorporating loading and error messages with the help of useContext and react hooks

Currently, I have a context.js file that makes an ajax call and stores the data in an array to be shared across components. While adding some 'loading ...' text during the loading process using axios, I feel there might be a better way to handle ...

What is the best way to eliminate the colon (:) from an API URL within a React project?

I'm encountering an issue while trying to fetch data from an API with a dynamic id. The problem seems to be stemming from the presence of a colon in my Route path. Upon debugging, I realized that the colon is being included before the id in the URL li ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

What are the steps to create a countdown timer that counts down in a precise number of seconds?

I'm struggling with the code below: var hours = Math.floor((timeLeft) / 3600); var minutes = Math.floor((timeLeft - (hours * 3600)) / 60); var seconds = Math.floor((timeLeft - (hours * 3600) - (minutes * 60))); if (hours < "10") { hours = "0" + ...

Can one conceal the JavaScript code that has been written?

Can JavaScript (jQuery) codes be hidden from view? I have a program with several load() functions and I'm worried that everyone can see the page addresses. Is this a risk? Example code snippet: load('account/module/message/index.php'); ...

What are the reasons that execCommand does not function correctly when attempting to justify text?

Why isn't justify with execCommand working properly? Take a look at the code below: $('#JustifyLeft').click(function(){ document.execCommand("JustifyLeft", false, ""); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2 ...

Transform numerous paths into an array of offspring using Javascript

I'm looking for the most efficient way to transform multiple arrays with various paths into a single flat array of children. I attempted using object references, but encountered an issue with an endless loop. Are there any alternative methods I could ...

What is the process for incorporating a script function into a React application?

Recently, I've been attempting to integrate the external application Chameleon into my React application. To achieve this, I need to incorporate the javascript function within my application. I prefer it to be invoked only in specific scenarios, so I ...

How can I delete cached AJAX POST requests for a web app on the iOS6 home screen?

We are currently facing a significant issue with iOS6 ajax POST request caching in our webApp. After the upgrade, most of our users who have added the app to their home screen are experiencing problems with stale data being retrieved from over 6 days ago. ...

Angular routes cause a glitch in the Bootstrap navbar, causing it to shift to the left on certain active

Apologies for the simple question, I am new to web design and couldn't find a solution even after extensive googling and searching. The issue I am facing is that when clicking on "EX5" or "EX6" in my navbar, it shifts to the left side of the screen i ...