javascript - 如何将不同的位置放在随机添加的图像上? Vue.js

标签 javascript arrays vue.js vuejs2

我有这个:每一秒,所有图像都会移动到相同随机位置screenshot

但我想要这样:每一秒,我在不同的位置都有一个新图像

JavaScript:

const vue = require("@/assets/images/vue.png");
const bootstrap = require("@/assets/images/bootstrap.png");
const bulma = require("@/assets/images/bulma.png");

export default {
  name: "randImg",
  data() {
    return {
      images: [
        vue,
        bootstrap,
        bulma,
        css3
      ],
      addedImage: [],
      imgTop: -100,
      imgLeft: -100,
      imgHeight: 64,
      imgWidth: 64,
      changeInterval: 1000,
      selectedImage: ''
    }
  },
  computed: {
    imgStyle() {
      return {
        top: `${this.imgTop}px`,
        left: `${this.imgLeft}px`,
        height: `${this.imgHeight}px`,
        width: `${this.imgWidth}px`
      }
    }
  },
  created() {
    this.randomImage();
    const randomImg = func => setInterval(func, this.changeInterval);
    randomImg(this.randomImage);
    randomImg(this.addImage);
    randomImg(this.randomPosition);
  },
  methods: {
    randomImage() {
      const idx = Math.floor(Math.random() * this.images.length);
      this.selectedImage = this.images[idx];
    },
    randomPosition() {
      const randomPos = twoSizes => Math.round(Math.random() * twoSizes);
      this.imgTop = randomPos(window.innerHeight - this.imgHeight);
      this.imgLeft = randomPos(window.innerWidth - this.imgWidth);
    },
    addImage(){
      this.addedImage.push(this.selectedImage);
    }
  }
}

HTML:

<img :style="imgStyle" class="image" :key="id" :src="image" v-for=" (image,id) in addedImage">

最佳答案

问题是您的图像被绑定(bind)到相同的计算 imgStyle,它将所有绑定(bind)图像的位置设置为相同的坐标。

要使位置唯一,每个 addImage[] 项都应包含自己的位置:

this.addImage.push({
  style: {
    top: `${this.imgTop}px`,
    left: `${this.imgLeft}px`,
    height: `${this.imgHeight}px`,
    width: `${this.imgWidth}px`
  },
  src: this.selectedImage
})

这将需要更新模板以绑定(bind)到每个迭代器项的子属性:

<img :style="image.style" 👈
     :src="image.src" 👈
     v-for="image in addedImage">

demo

关于javascript - 如何将不同的位置放在随机添加的图像上? Vue.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55301193/

相关文章:

javascript - 正则表达式计算字符串中的单词总数

php - 使用PHP数组将数据插入MYSQL

php - 使用 PHP 进行 MySQL 查询的 JSONArray 不适用于复杂的查询

javascript - $emit 在计算之前执行

javascript - 相当于java中的javascript date.setUTCSeconds(s)

javascript - jQuery 滚动 DIV : stop scrolling when DIV reaches footer

javascript - 如何在javascript中重命名对象属性?

vue.js/electron 如何列出公用文件夹中的所有文件夹名称

Vue.js 不显示像 {{ post.title }} 这样的括号

javascript - 如何迭代整个数组?然后更新数据库