[Vuejs]-How to bind y and x coordinates to an image in vue?

5👍

One solution is to bind an inline style that sets the absolute position of the <img>:

  1. Create an <img> tag:

    <img class="my-img">
    
  2. Style it so it’s absolutely positioned:

    .my-img {
      position: absolute;
    }
    
  3. Bind its style to an object that sets the top (Y-coordinate) and left (X-coordinate). In the following example, we bind top to a data field named imgTop and left to one named imgLeft. When our component sets imgTop, the <img>‘s top will be set to the same value; and similarly for left and imgLeft. We’ll add the imgTop and imgLeft data fields later.

    <img class="my-img" :style="{ top: imgTop, left: imgLeft }">
    
  4. Create a <div> to contain the <img>. This container will represent the clickable area, where the <img> can be moved.

    <div class="container">
      <img class="my-img">
    </div>
    
  5. Style the container to be as large as the viewport (using vw and vh length units):

    .container {
      width: 100vw;
      height: 100vh;
    }
    
  6. Set a click-event handler on the container. We use v-on:EVENT=METHOD to assign a method that handles the event (there’s also a shorthand syntax for this — @EVENT=METHOD). We’ll add the onClick method later.

    <div class="container" @click="onClick">
    
  7. Create the imgTop and imgLeft fields in your component’s data:

    extern default {
      data: () => ({
        imgLeft: null,
        imgTop: null,
      }),
    }
    
  8. Create the event-handler method in your component’s methods. Note the handler formats the MouseEvent.clientX and MouseEvent.clientY into pixel lengths (appends px), and assigns the results to imgLeft and imgTop.

    extern default {
      methods: {
        onClick(e) {
          this.imgLeft = `${e.clientX}px`;
          this.imgTop = `${e.clientY}px`;
        }
      }
    }
    

Demo:

new Vue({
  el: '#app',
  data: () => ({
    imgLeft: null,
    imgTop: null,
  }),
  methods: {
    onClick(e) {
      this.imgLeft = `${e.clientX}px`;
      this.imgTop = `${e.clientY}px`;
    }
  }
})
.container {
  width: 100vw;
  height: 100vh;
}

.img {
  position: absolute;
}
<script src="https://unpkg.com/vue@2.5.17"></script>

<div id="app">
  <div class="container" @click.stop="onClick">
    <img class="img"
         src="//placekitten.com/100/100"
         width="100"
         alt="kitty"
         :style="{top: imgTop, left: imgLeft}">
  </div>
</div>
👤tony19

Leave a comment