Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mouse coordinates in VueJS

I have a component triggered with v-on:click="someMethod".

How would I get the mouse coordinates (X, Y) of this click?

Additional information: HTML5 Canvas component

like image 630
Luiz Avatar asked Aug 07 '17 18:08

Luiz


2 Answers

Vue passes the event as the first parameter in the method. If parameters, use this instead: someMethod(param1, param2, event)

    methods: {
        someMethod(event) {
            // clientX/Y gives the coordinates relative to the viewport in CSS pixels.
            console.log(event.clientX);
            console.log(event.clientY);

            // pageX/Y gives the coordinates relative to the <html> element in CSS pixels.
            console.log(event.pageX);
            console.log(event.pageY);

            // screenX/Y gives the coordinates relative to the screen in device pixels.
            console.log(event.screenX);
            console.log(event.screenY);
        }
    }
like image 173
kevguy Avatar answered Nov 12 '22 22:11

kevguy


Like you would in any event handler

new Vue({
  el: '#element',
  methods: {
    someMethod: function (event) {
      var x = event.pageX;
      var y = event.pageY;
    }
  }
})

There's also clientX and screenX, they return somewhat different results based on the viewport, the screen or the rendered content.

like image 6
adeneo Avatar answered Nov 12 '22 22:11

adeneo