I want to resize (as in reduce the filesize if it exceeds limit) an Image using canvas. I see that the resultant image size drawn on canvas, keeping the width and height constant, results in different file size depending upon what has been drawn on canvas.
I am willing to reduce the resolution further provided I get the desired file size.
How do I make sure whatever the resolution I get file(image) size within the limit?
Refer to this fiddle
var el = document.getElementById('f');
el.addEventListener('change', onChange);
function onChange(e) {
  var file = this.files[0];
  console.log("CHANGING");
  var fr = new FileReader();
  fr.onload = function(e) {
    drawOnCanvas(e.target.result);
  }
  fr.readAsDataURL(file);
}
function drawOnCanvas(imgSrc) {
  var canv = document.createElement('canvas'),
    img = new Image();
  console.log("DRAWING");
  canv.width = canv.height = 500;
  ctx = canv.getContext('2d');
  img.onload = function() {
    console.log("IMAGE LOADED");
    ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canv.width, canv.height);
    try {
      document.body.removeChild(document.querySelector('canvas'));
    } catch (e) {}
    document.body.appendChild(canv);
    blob = canvasToFile(canv.toDataURL());
    alert("FILE SIZE " + blob.size);
  }
  img.src = imgSrc;
}
function canvasToFile(dataUrl) {
  var encData = dataUrl.split(',')[1],
    binString = atob(encData),
    binData = new Uint8Array(binString.length),
    i, blob;
  for (i = 0; i < binString.length; i++) {
    binData[i] = binString.charCodeAt(i);
  }
  blob = new Blob([binData], {
    type: 'image/jpeg'
  });
  return blob;
}<p>Try uploading different image file and see the difference in size for same output resolution:</p>
<input type="file" id="f"> 
     
    