David Tan David Tan - 3 months ago 13
Javascript Question

How to pass a parameter to a built-in function's callback? (i.e. HTMLCanvasElement.toBlob)

I would like to do checks against the resulting Blob, which requires me to pass my own variable to the callback. However,

only passes the Blob. How can I pass my own variable to the callback? Or, is there a better method to accomplish this that doesn't involve passing a parameter to the callback?

Example of desired usage:

canvas.toBlob(processImage(blob, inputImage, resolutionMultiplier), "image/jpeg", Math.max(quality, 1) / 100)

function processImage(newBlob, inputImage, resolutionMultiplier) {
console.log(URL.createObjectURL(newBlob));
if (newBlob.size > inputImage.size * 0.9 && inputImage.size < 1048576) {
//use original image
} else if (newBlob.size < inputImage.size * 0.9 && newBlob.size < 1048576) {
//use newblob
} else if (newBlob.size >= inputImage.size * 0.9 || newBlob.size >= 1048576) {
//compress again with lower quality
}
}

Answer

Your use case isn't entirely clear from your question, but in general you'd simply pass the custom variable through a closure:

var oldSize = ...;

function callback(blob) {
    if (blob.size < oldSize) {
        // take appropriate action
    }
}

canvas.toBlob(callback);

An alternative might be to bind the oldSize as an argument:

function callback(oldSize, blob) {
    // ...
}

var oldSize = ...;

canvas.toBlob(callback.bind(null, oldSize));
Comments