18645: Uncaught TypeError: Cannot read property 'elt' of undefined

So I'm writing some code which has to do with the use of images.

var img = [];
var imgs = [];

function preload() {
  img[0] = loadImage("images/egg1.jpg");
  img[1] = loadImage("images/egg2.jpg");
  img[2] = loadImage("images/egg3.jpg");
}

var i_ = new Imgs(circles[n].x, circles[n].y, img[random(0,2)]);
imgs.push(i_);

function Imgs(x_, y_){
  this.x = x_;
  this.y = y_;
  this.img;

  this.update = function(){
    this.img = imgs[random(0,2)];
    image(this.img, this.x, this.y);
  }
}

So I am trying to display a random Image every time I click on an object. Therefore I created an object which gets the x and y value and the image which it should display (as an array of preloaded images). I tried a lot of different versions of this (without creating an object and an array of images) but every time I try to display a random image, this weird error occures: 18645: Uncaught TypeError: Cannot read property 'elt' of undefined.

(I think) the problem is this part: img[random(0,2)] If i write img[0] the image is normally displayed but if I use a random value or a variable, the error message comes up.

I saw this problem in another post but unfortunately the answers didn't help me. PS: please excuse my bad writing.

Tagged:

Answers

  • I know how the random function works (I didn't use is wrong did I?) but it also doesn't work if I use a variable instead...

  • Pay attention at the 3rd example there. I-)

  • well ... it took me about an hour to not realize how to get a random spot in an array ... But thank you :)

  • edited April 2017

    If you prefer a more traditional approach, similar to what we have to do in Processing Java, recall that random() returns a fractional value. But array indices are integer! =;

    Therefore we've gotta remove the fractional part of the resultant random value. :>
    There are many ways to pull that out in JS. But my favs are | 0 & ~~: :P
    img[~~random(img.length)]

    But in p5.js, you should take advantage of its easier API, as random()'s 3rd example: :>
    random(img)

Sign In or Register to comment.