Save a Three.js 3D model from different angles (Right, Left, Front, Back) and export it in PNG format

Hey there!

I'm currently working on a project involving a 3D shoe simulator, where I need to capture accurate images of the model from different angles (right, left, front, back) in PNG format.

I've set up routines to position the model in various views and have created a method called saveImage() that resets the views and captures the image data using toDataURL before sending it to a PHP page.

However, when calling these methods in sequence, the image is always saved from the last selected view. It seems like the Canvas renderer is not getting enough time to update.

Is there a way for me to capture the views (right.png, left.png, front.png, back.png) of my model using Three.js and save them on the server?

Below is the code I have developed:

Thank you for your help

Model 3D Right Position

Model 3D Left Position

Code


    /*
      Front
    */
    function front()
    {
      center();
      new TWEEN.Tween( { y: mesh.rotation.y} )
          .to( { y: mesh.rotation.y - 1 }, 150 )
          .onUpdate( function () {
                      mesh.rotation.y = this.y;
          }).start();
    }

    /*
      Back
    */
    function back()
    {
      center();
      new TWEEN.Tween( { y: mesh.rotation.y} )
          .to( { y: mesh.rotation.y - 4 }, 150 )
          .onUpdate( function () {
              mesh.rotation.y = this.y;
          } )
          .start();
    }

    /*
      Left
    */
    function left()
    {
      center();
    }

    /*
      Right
    */
    function right()
    {
      center();
      new TWEEN.Tween( { y: mesh.rotation.y} )
          .to( { y: mesh.rotation.y -2 }, 150 )
          .onUpdate( function () {
              mesh.rotation.y = this.y;
          } )
          .start();
    }

    /*
      Center
    */
    function center()
    {
      camera.position.set(-10,100,200);
      camera.lookAt(scene.position);
      mesh.scale.set(30,30,30);
      mesh.position.x = 0;
      mesh.position.y = 0;
      mesh.position.z = 25;

      mesh.rotation.x = 0.1;
      mesh.rotation.y = 15;
      mesh.rotation.z = 0;
    }

    /*
     Save the visions (right, left) in PNG
    */
    function saveImage()
    {
        right();
        ajaxSave("right");

        left();
        ajaxSave("left");
    }

    function ajaxSave(view)
    {
        var imgData = renderer.domElement.toDataURL("image/png");
        try { 
            $.ajax({
                  type: "POST",
                  beforeSend: function (xhr) {
                    xhr.setRequestHeader("Content-Type", "application/upload");
                  },
                  url: "save3d.php?img=" + view,
                  data:imgData
            });
        } 
        catch(e) {
            console.log("Browser without support for 3D recording.");
            return;
        }
    }

Answer №1

It appears that Malk's observation is accurate; the view is being tweened before taking a snapshot, causing the snapshot to capture the view mid-tween. One solution could be to modify the functions to accept an argument indicating whether to tween or not. For example:

/*
  Front
  parameter: twe: Boolean : If tween or not
*/
function front(twe)
{
  center();
  if(twe){
    new TWEEN.Tween( { y: mesh.rotation.y} )
        .to( { y: mesh.rotation.y - 1 }, 150 )
        .onUpdate( function () {
                    mesh.rotation.y = this.y;
        }).start();
  }else{
    mesh.rotation.y - 1;
  }
}

Alternatively, setting up additional cameras in the desired positions and switching to them before taking the snapshot could also work.

On a lighter note, the term "shoe simulator" provided some amusement for me.

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

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...

What steps should I take to enable Google Maps style on mobile devices?

Hi there! I'm having some trouble styling my Google map. Sometimes the style loads correctly in browsers, and sometimes it doesn't. Another issue I've noticed is that when I view the page on mobile platforms like Android Chrome, iOS Safari, ...

A more effective approach than relying on an abundance of else if statements

I need to improve my Javascript code that handles different text options: var personUrls = { 'amy': 'http://www.mydomain.com/amylikescats.html', 'dave': 'http://www.mydomain.com/daveshome.html', 'steve': & ...

Tips for generating a selection of option tags from a JSON file using ReactJS

I am currently exploring ReactJS and experimenting with forms. My current project involves creating a list of <option> tags based on the data stored in a local JSON file. After debugging the code, I can confirm that the values are being correctly re ...

How can I combine multiple objects into a single array using JavaScript?

I am currently facing the following situation: [{"title":"007 Legends"},{"title":"0 Day Attack on Earth"},.....] After running this query, I get the following result: `exports.findAll = function(req, res){ items.find({},{_id:0},function(err, results ...

Guide to using jQuery to dynamically transfer text from a textbox to a label within a div

I am working with a ViewBag in my code <div id="amount"><h4>@ViewBag.Amount</h4></div> What is the best way to update the amount using jQuery? I have an input field for the new amount <input type="text" class="form-control" id ...

Display varying amounts of pictures in varying resolutions

On my website, I want to display a row of 5 images that are resized using media queries to fit the screen. The challenge is that on smaller screens like an iPhone 5S, I only want to show 3 images instead of 5. On larger screens like iPad or other devices, ...

Creating a dynamic Flash website integrated with a Joomla platform?

Many websites today showcase content that loads and displays with creative effects, all without the need for a page refresh. It's truly magical. Websites like pandora.com, groveshark.com, and hypem.com are perfect examples of sites that have music pla ...

Button for Autocomplete Component in React Material UI to be displayed after clearing the field

After successfully adding a search button to my Autocomplete Component on Material UI, I encountered an issue where the button always appears before the clear button as shown in this image: https://i.sstatic.net/Tx5zv.png I am seeking assistance on how t ...

Styling material-ui textfield: Tips and tricks

I've been grappling with figuring out how to customize a material-ui TextField component. <TextField id="email" label="Email" className={classes.textField} value={this.state.form_email} onChange={this.handle_change('form_e ...

Is there a way to access and read the console log of a specific website using Python code? I am looking to extract messages such as "ok" and "connected

Seeking guidance on how to interpret console log output for a specific website while automating with Python. Struggling to extract live console data through Selenium, as there's no built-in function for reading logs in real-time. Although I can acces ...

Windows Angular experienced a failure during allocation as the mark-compacts near heap limit were ineffective

Encountering an error in my Angular application on Windows10 when using ng build --prod, but it works fine with ng build. The issue seems to arise from the presence of 4 JSON files in the assets folder, with one file being 21 MB and the others ranging fro ...

Is it possible for me to use the name "Date" for my component and still be able to access the built-in "new Date()" functionality?

Currently following the NextJS tutorial, but adding my own twist. In the NextJS example, the custom component is named "Date" (/components/date.js) and does not utilize the built-in Date() object in processing, making it unique to the file. In my scenario ...

Attitude: Defiant and Ignoring Authority

So far, no suggestions have been made, indicating that maybe I haven't properly summarized the issue; The problem arises when I absolutely position the section with the class="container" using an additional class or id specific to that <div>. I ...

NPM encountered an issue that prevented it from scanning directories due to a permission denial with the error code E

Whenever I type "npm run build:prod" build:prod npm run build -- --configuration production --aot --optimization=false I encounter the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e4e3ece1fbafece3 ...

Blocking the page with AJAX async set to false is necessary in order to retrieve the value successfully

In my current setup, I have implemented an ajax request within im.js to communicate with my PHP server from JavaScript and receive feedback. However, I am facing an issue where I need to update a variable based on the callback of the .ajax function. Here i ...

What are the best options for storing small data in a React or Next.js project?

As I work on my personal portfolio using Next.JS, I've come to a point where I need to display multiple projects each with their own set of information like images, titles, and links. I'm wondering where would be the best place to store this data ...

What is the best way to update a form input value using React and Redux?

I am currently facing a challenge with handling input changes. I have experience doing this in React, but now that I am also using Redux, I am unsure of how to update values in the inputs. When I try typing letters, nothing happens. Could you guide me on ...

python code for transforming images

I am on the search for a method to convert one image into another. The "Unified Transform Tool" in GIMP has been ideal for this task, but I am curious if it can be done using a Python library like openCV or PIL? My objective is to seamlessly insert images ...

Steps for building a 2x2 grid of tables in HTML

I am struggling to design a 2x2 grid of collapsible tables in HTML. I have been experimenting with different solutions, but I haven't found one that works seamlessly. When I collapse the top left table, it messes up the alignment of the bottom row tab ...