Home » vue » Vue.js – Animate image as cursor moves horizontally

Vue.js – Animate image as cursor moves horizontally

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’ve got a number of images (around 31), The objective is for the page to load with image 1 displayed, then as the cursor runs horizontally, we animate through the images depending on the cursor location.

So far, I’ve got the following method set up

handleMouseMove(evt) {
  var e = evt || window.event;
  var x = e.offsetX;
  this.width = this.$refs.barrelapp.clientWidth;
  this.divisions = this.width / 31;
  this.position = x;
}

I have this to fire on mousemove over the image element… Which fires and correctly gives me the width of the element, the amount of pixels we should fire each image src, and the current mouse position.

Could anyone shed any light on how I could maybe index this, and run over an array of the 31 images, or something along those lines?

For example, If i have back a width of 1280 and divisions of 41.290322580645, I’d like it to fire an image change on every 41.290 etc pixels.

I’m very new to Vue! So please excuse me if I’ve missed something really obvious!

Ideally, I’d like this to work from left to right, and vice versa!

Thanks guys.

Answers:

you could do something like this…

<script>
export default {
  data() {
    return {
      imageIndex: 0
      images: [
        // images
      ]
    }
  },
  computed: {
    image() {
      return this.images[imageIndex]
      // or if you're using bg image style
      return {
        'background-image': `url(${this.images[imageIndex]})`
      }
    }
  },
  methods: {
    handleMouseMove(evt) {
      const e = evt || window.event;
      const x = e.offsetX;
      const width = this.$refs.barrelapp.clientWidth;
      const divisions = width / this.images.length;
      this.imageIndex = Math.floor(x / divisions);
    }
  },
}
</script>

this assumes you have the images as an array of strings in the data object. You can then use the computed called image to display the relevant image