How to incorporate click and drag feature for rotating a 3D object using vue.js

Whenever I click a button, the rotation function is activated and allows me to rotate an object by hovering over it with my mouse.

Now, I want to modify this behavior so that the object rotates only when I click on it and move the mouse (while holding down the mouse button). The rotation should stop once I release the mouse button.

Here's my code:

HTML:

<div class="model__3d" ref="panel3d">   
<a class="button" @click.prevent="rotatemouse()">360</a>

JavaScript Code:

rotatemouse() {

        document.querySelector('.model__3d').addEventListener('mousedown', () =>{
            document.onmousemove = handleMouseMove;
        });

        //document.onmouseup = function () {
            document.querySelector('.model__3d').addEventListener('mouseup', () =>{
            document.onmousemove = null;
        });


        //function handleMouseMove(event) {
           document.querySelector('.model__3d').addEventListener('mousemove', (event) =>{
            let eventDoc, doc, body;

            event = event || window.event;

            if (event.pageX == null && event.clientX != null) {
                eventDoc = (event.target && event.target.ownerDocument) || document;
                doc = eventDoc.documentElement;
                body = eventDoc.body;

                event.pageX = event.clientX +
                    (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
                    (doc && doc.clientLeft || body && body.clientLeft || 0);
                event.pageY = event.clientY +
                    (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
                    (doc && doc.clientTop  || body && body.clientTop  || 0 );
            }

            if(maxX == 0){
                maxX = event.pageX;
            }

            if(maxY == 0){
                maxY = event.pageY;
            }

            if(event.pageX > maxX){
                console.log("Right");
                this.model.rotation.y = this.model.rotation.y + 0.08;
                maxX = event.pageX;
            }
            else {
                console.log("Left");
                this.model.rotation.y = this.model.rotation.y - 0.08;
                maxX = event.pageX;
            }

            if(event.pageY > maxY){
                console.log("Up");
                if(this.model.rotation.x < 0.32)
                    this.model.rotation.x = this.model.rotation.x + 0.08;

                console.log(this.model.rotation.x);

                maxY = event.pageY;
            }
            else {
                console.log("Down");
                if(this.model.rotation.x > -0.25)
                    this.model.rotation.x = this.model.rotation.x - 0.08;

                console.log(this.model.rotation.x);
                maxY = event.pageY;
            }
        });
    }

Thank you!

Answer №1

To achieve the desired functionality, you can utilize a combination of @mousemove, @mousedown, and @mouseup events.

new Vue({
  el: '#app',
  data: {
    captureToggle: false,
    x: 0,
    y: 0
  },
  methods: {
    mo: function(evt) {
      if (this.captureToggle) {
        this.x = evt.x
        this.y = evt.y
      }
    },
    captureOn: function() {
      this.captureToggle = true
    },
    captureOff: function() {
      this.captureToggle = false
    }
  }
})
#app {
  margin: 50px;
}

.mouseArea {
  height: 100px;
  width: 300px;
  border: solid thin;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <div class="mouseArea" @mousedown="captureOn" @mouseup="captureOff" @mousemove="mo"></div>
  <div>x : {{x}}</div>
  <div>y : {{y}}</div>
</div>

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

When utilizing ASP.NET Core Razor pages for file uploads and utilizing AJAX Post to send the file to an IFormFile handler, the request

I have a straightforward task that involves uploading a file and using AJAX to post it to the Index page: <input type="file" id="file-selector" accept=".txt"> Here is the corresponding Javascript: const fileSelector ...

You are unable to insert a variable within the channels.get() method in discord.js

Attempting to troubleshoot this issue has been quite frustrating. Despite my efforts, it seems that something is not working as expected. I can't help but wonder if I am simply overlooking a simple mistake due to fatigue. Here's the scenario: It ...

Run audio player in the background with Google Chrome Extension

I am working on an extension and I want to have a page with an audio player that continues to play even when I click outside of the extension. I tried using the "background" attribute in the manifest file, but it seems to only work with javascript files. ...

Angular's ngOnDestroy lifecycle hook does not execute as expected after a button click event

When working on my HTML code, I encountered the following: <div class="form-group"> <button type="submit" value="submit" class="btn btn-secondary btn-float">Upload</butt ...

Creating files for two HTML pages with Vue: A step-by-step guide

Currently, I am working on creating two HTML files as part of my project structure. This is how it looks: |- node_modules |- public | |- blog | | |- some-page.html | |- index.html |- src (contains all the Vue components) |- Blog.Vue |- Index.Vue ...

Performing XMLHttpRequests and ajax requests inside a foreach loop

I am facing a issue with echoing the decoded array using var_dump. Each time I click the button, a unique xmlhttprequest and ajax call should get executed for every row. However, in reality, the ajax doesn't work as expected. Upon examining the source ...

Incorporate the Vue JS response into the table component

I am attempting to append my response from Vue into a table but I am unable to do so and I don't know why. I can retrieve all the data from my database, I can see it in my web browser console, but my table remains empty. Below is my current code: Vu ...

Showing code snippets with possible markup or malicious content as plain text strings

I am facing a challenge with a table on my webpage where values are added through a textbox in a popup modal. However, when I try to add the string ); to the textbox, it triggers a popup instead of being displayed innocuously in its original format on the ...

What could be causing my AJAX code to fail in retrieving information from an API?

Hey everyone, I'm new here and hoping to get some help with an issue I'm facing. I've written a code to fetch data from an API and display it on my HTML page, but for some reason the AJAX code isn't working. There's nothing showing ...

What is the most efficient way to retrieve the key at a specific index within a JavaScript map object?

If I have the map object shown below: const items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']]) I am trying to retrieve the key at index 2. Is there a method other than using a for ...

Is there a way to replicate ajaxStart and ajaxStop functions without using jQuery?

After reviewing the extensive jQuery code, I'm wondering if this task would be simple to accomplish. Any suggestions on how to approach it? I'm interested in using this not for a webpage, but for a C# application that needs to monitor ajax activ ...

The Vue project is unable to locate the '@' symbol

After upgrading to vue-cli version 4.5.15, I encountered an issue where it couldn't resolve @ as ./src and all paths using '@' were not found. Can anyone explain why this is happening and suggest a possible solution? https://i.sstatic.net/P ...

How can I make sure my rows are properly aligned using the Grid

Looking at the image below, I am attempting to align "Ticket Number" and "Email" using a Grid: View My Result Image <Grid container direction="row" justifyContent="flex-start" alignItems="stretch" style={{ pad ...

Inserting additional information and assigning a category following a prosperous AJAX request accompanied by output from php echo

I'm currently working on implementing an AJAX call to my PHP file to send an email once a contact form is submitted. Initially, I had everything functioning properly where the response from PHP was displayed in a div above the form. However, I wanted ...

Don't attempt to fetch data using Vuejs and Laravel with relationships if you can't retrieve it

When working in the controller, I receive a response with status code 200. return = CustomerRequest::with('item')->paginate(5); Within the model class: public function item() { return $this->belongsTo('App\Item'); } Imp ...

Having trouble with the JSFiddle dropdown button that is unresponsive to

I am currently in the process of developing a test drop-down menu. The open menu button functions correctly, however, the close button is unresponsive to clicking or hovering actions. Upon clicking the open menu button, it should make the other button visi ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...

Display sqllite database information in an HTML view using Ionic 2

After executing a select query against the database, I am able to read the results from the logcat and view the data there. However, I am encountering an issue where the data is not rendering in the HTML view after binding. //data retrieve section db.exec ...

Vue.js component displays content without waiting for API response

I have developed two components that will display different content based on the response from an API. If the Promise does not resolve or resolves with an empty object, an error notification card will be rendered. If the Promise resolves with data, t ...