a small batch of dynamically generated graphics created with Vue

Trying to create a div with randomly positioned icons and here's what I have so far. Is there a way to limit the number of images generated to just 20, instead of unlimited?

If you know of a better method for achieving this, I would greatly appreciate your input.

Thank you

let nextId = 20

new Vue({
  el: '#app',
  data() {
    return {
      images: [
        '//placekitten.com/200/200',
        '//placekitten.com/200/201',
        '//placekitten.com/200/202',
        '//placekitten.com/200/203',
        '//placekitten.com/200/204',
      ],
      addedImage: [],
      imgTop: -100,
      imgLeft: -100,
      imgHeight: 64,
      imgWidth: 64,
      changeInterval: 10,
      selectedImage: ''
    }
  },
  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({
        style: {
          top: `${this.imgTop}px`,
          left: `${this.imgLeft}px`,
          height: `${this.imgHeight}px`,
          width: `${this.imgWidth}px`
        },
        src: this.selectedImage,
        id: nextId++
        
      });
    },
  }
})
.image {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <img :style="image.style" class="image" :key="image.id" :src="image.src" v-for="image in addedImage">
</div>

Answer №1

Declare variables to keep track of the total, current count, and reference for intervals:

limit: 20,
counter: 0,
interval: null

Consolidate the three instances of setInterval into one and save the interval.

created() {
  this.interval = setInterval(() => {
    this.randomImage();
    this.randomPosition();
    this.addImage();
    this.counter++;
    if (this.counter === this.limit) {
      clearInterval(this.interval);
    }
  }, this.changeInterval);
},

Every call increments the counter, and once the limit is met, the interval is stopped. Check out this demonstration:

let nextId = 20

new Vue({
  el: '#app',
  data() {
    return {
      images: [
        '//placekitten.com/200/200',
        '//placekitten.com/200/201',
        '//placekitten.com/200/202',
        '//placekitten.com/200/203',
        '//placekitten.com/200/204',
      ],
      addedImage: [],
      imgTop: -100,
      imgLeft: -100,
      imgHeight: 64,
      imgWidth: 64,
      changeInterval: 10,
      selectedImage: '',
      limit: 20,
      counter: 0,
      interval: null
    }
  },
  created() {
    this.interval = setInterval(() => {
      this.randomImage();
      this.randomPosition();
      this.addImage();
      this.counter++;
      if (this.counter === this.limit) {
        clearInterval(this.interval);
      }
    }, this.changeInterval);
  },
  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({
        style: {
          top: `${this.imgTop}px`,
          left: `${this.imgLeft}px`,
          height: `${this.imgHeight}px`,
          width: `${this.imgWidth}px`
        },
        src: this.selectedImage,
        id: nextId++
      });
    },
  }
})
.image {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <img :style="image.style" class="image" :key="image.id" :src="image.src" v-for="image in addedImage">
</div>

Answer №2

To overcome this issue, I implemented a solution involving a condition based on the array's length.

We can specify the desired number of images by defining the length parameter. For instance, if we aim to have 20 images, we can include the following code snippet:

   addImage(){
        if (this.addedImage.length < 20) {
            this.addedImage.push({
                style: {
                    top: `${this.imgTop}vh`,
                    left: `${this.imgLeft}vw`,
                    height: `${this.imgHeight}px`,
                    width: `${this.imgWidth}px`
                },
                src: this.selectedImage,
                id: uniqueId++

            });
        }
    }

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

Set a placeholder to display when Vuex has completed loading

How can I properly handle loading state after dispatching in Vue? Currently, when trying to set loading state to true before dispatch and false after, the following code does not work: this.loading = true; this.$store.dispatch('items', data); t ...

Is there a way to connect an HTML page without using a hyperlink?

Is there a way to directly display linked HTML pages on my webpage instead of just creating a link? I'm looking for suggestions on how to arrange this. Thank you! ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Activate the input autofocus feature when displaying a dialog in Vue.js

When opening a dialog with input text using v-menu upon clicking a button, how can I focus on the input text field? I have attempted to use $ref but it does not seem to work. newFolderClick(){ this.$refs["input_new_folder"].focus(); //it still appea ...

Using Javascript to trigger form submission using arrow keys

There are four forms displayed on a single page, and I want each form to be submitted based on the arrow key that is pressed. <form name='go_north' action='' method='post'> <input type='hidden' name=' ...

Utilizing Vue to post an object for custom Laravel Excel export functionality

I'm currently facing a dilemma. I am working on creating an export feature using Maatwerk Laravel-Excel. The goal is to allow the user to apply filters before downloading the data. In Vue, I plan to capture the selected values as per user input. Upon ...

Creating a Vue.js component that animates text to fade in and out within a textarea when a button

I need assistance with updating a <textarea> element in my Vue application. Currently, I have the textarea bound to some data in my state. However, when a button is clicked, I want the existing data in the textarea to fade out and be replaced with ne ...

The excessive use of Selenium Webdriver for loops results in multiple browser windows being opened simultaneously, without allowing sufficient time for the

Is there a way to modify this code so that it doesn't open 150 browsers to google.com simultaneously? How can I make the loop wait until one browser finishes before opening another instance of google? const { Builder, By, Key, until } = require(& ...

Substitution of "with" operator in strict mode

Let's say I have a user-entered string value stored in the variable f. For example: f = "1/log(x)"; In vanilla JavaScript, I used the following operator: f = "with (Math) {" + f + "}"; While this code worked perfectly fine in vanilla javascript, i ...

Flawed reasoning in determining the selection of checkboxes

Take a look at the code snippet below, featuring multiple checkboxes with corresponding fields: <Checkbox checked={checked[element]} onChange={(e) => { setChecked({ ...checked, [e.target.name]: !checked[e ...

Refreshing a component in Angular/Angular2 using routerLink from the NavBar when already on the current route

When I am on the same route and click again from the navbar, nothing happens. Is there a way to refresh my component directly from the navbar using a method in routerLink? <li [routerLinkActive]="['active']"><a [routerLink]="['/ca ...

Please make another request in 1 minute using an observable

I am looking to continuously load data from 5 API's every minute in order to refresh the page. My approach involves using Observable.forkJoin to gather all the data by sending requests simultaneously and then placing it inside a setInterval function. ...

Steps for creating duplicates of jQuery elements

My Objective I am currently working on a project that involves allowing users to modify an SVG file based on input, such as text formatting (bold, italic, etc.). It is important that the user can revert back to the original template without having to relo ...

Vue.js is unable to add elements to a nested array

I'm new to Vue and Stack Overflow, so I apologize if this isn't the right place to ask. I've been working on a small project for a few days and I need some help. I want to be able to enter multiple customer names and then add as many childre ...

Filtering an object using data in AngularJS

My current data object structure looks like this : $scope.data = [ { "name": "1001", "queue": [ { "number": "111", } ] }, { "name": "1002", "queue": [ ] ...

Developing a Chessboard Using JavaScript

Seeking help with a Javascript chessboard project. I have successfully created the board itself, but facing difficulty assigning appropriate classes (black or white) to each square. Managed to assign classes for the first row, struggling with the remainin ...

having trouble with developing a dropdown menu using jquery

I'm currently creating a drop-down menu for my website and here is the code I'm using: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html dir="ltr"> <head> <met ...

Selenium WebDriver imitates the mouse movement event by utilizing non-zero values for movementX and movementY

I am trying to test my web application using selenium webdriver, but I am having trouble getting the mousemove event to trigger with values other than 0 for movementX or movementY. I have attempted to use Class: Selenium::WebDriver::ActionBuilder: driver ...

Navigating child components within a flat list using React Native

Hello everyone, I am relatively new to React Native and JavaScript, and I'm currently trying to grasp the concept of react native navigation. In my project, I have a home screen that contains a CardFlatList component with multiple CardComponents. The ...

What could be causing the error message "Why is property 'value' not found in null?" to appear in my code?

I keep encountering the "Cannot find property 'value' of null" error on line 2 of my JavaScript code. Despite entering text in the text-box, I am unable to resolve this issue. Is there a solution to fix this problem? HTML: <!DOCTYPE html> ...