How insert into collection — after image from URL has loaded

I’m trying to calculate the width and height of an image loaded via URL. And then insert a new document with the image URL and the calculated dimensions. How can I wait with insert until the image dimensions have been calculated?

At the moment I have to load the same image-URL twice — then the dimensions are calculated and inserted correctly.

Has this to be done with a callback? I still find it confusing … Thanks!

Template.body.events({
  'submit .new-pic'(event) {
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form target
    const target = event.target;
    const imgUrl = target.url.value;

    // Create Image Object
    // and set up dimensions from URL
    let img = new Image();
    img.src = imgUrl;
    let imgWidth = img.width;
    let imgHeight = img.height;

    // Insert into Collection
    MyCollection.insert({
      imgUrl,
      createdAt: new Date(),
      dimensions: { width: imgWidth, height: imgHeight },
    });
    // Clear form
    target.url.value = '';
  },
});

img.onload did the trick:

Template.body.events({
  'submit .new-pic'(event) {
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form target
    const target = event.target;
    const imgURL = target.url.value;

    // Create Image Object
    let img = new Image();
    img.src = imgURL;
    
    // Insert into Collection
    img.onload = function() {
      myCollection.insert({
        url: imgURL,
        createdAt: new Date(),
        dimensions: { width: this.width, height: this.height }
      });
      // Clear form
      target.url.value = '';
    };
  }
});
1 Like