mardi 12 mars 2019

How to randomly generate new image Javascript(Vue.js)?

I am using vue-cli project and now here is not so clean Vue.js but i firstly want my project to work! i would like to show you my JavaScript:

const bootstrap = require("./assets/bootstrap.png");
const bulma = require("./assets/bulma.png");
const css3 = require("./assets/css3.png");

const images = [
  bulma,
  bootstrap,
  css3
];

const idx = Math.floor(Math.random() * images.length);
const randomImage = images[idx];

export default {
  name: "app",
  data() {
    return {
      images,
      idx,
      randomImage
    };
  },
  methods: {
    createImage() {
      const x = document.createElement("IMG");
      x.setAttribute("src", randomImage);
      x.setAttribute("id", "picture");
      document.body.appendChild(x);
    },
    animate() {
      let self = this;
      self.createImage();
      const elem = document.getElementById("picture");
      let pos = 0;
      elem.style.left = Math.round(Math.random() * 100) + "%";
      elem.style.display = "block";
      let id = setInterval(frame, 20);
      function frame() {
        if (pos === 110) {
          clearInterval(id);
          elem.style.display = "none";
          self.animate();
        } else {
          pos++;
          elem.style.top = pos + "%";
        }
      }
    }
  }
};

Now i have 2 problems! 1: my image is generating randomly only when i reload page, but when i start animation there will be only one image... i've created randomImage for that, you can see it 2: i don't understand how to delete that image when it is on the bottom! i decided to use elem.removeChild(self.x); (self means .this) but it doesn't work, i have an error like "Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'."

So, please help me guys!

By the way this is this project if you need everything is in App.vue https://github.com/GermanVaranytsya/german-cv




Aucun commentaire:

Enregistrer un commentaire