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 = '';
},
});