Scaling Images with HTML5, October 4, 2016
You've probably noticed that a number of web applications that deal with images will
automatically resize your images on the fly. You might imagine that they use some sort
of special plugin to make the magic happen, but the truth of the matter is that support
for this operation is baked right in to HTML5. You just have to know how to use it.
There is more than one way to skin this cat, but the basic procedure is this:
Once the image is uploaded, use the FileReader API to get the contents of the image as a data URL.
Instantiate a new Image object and set its URL to the data URL obtained in step 1.
Create a canvas element, but do not add it to the page.
Do the math to compute the dimensions of the resulting scaled image and assign them to the
width and height properties of the canvas element.
Get a 2D context object for the canvas Call the drawImage function on the context, passing in
the Image object, 0 for the left and top coordinates, and the dimensions of the newly scaled
image as the right and bottom coordinates.
Call the toDataURL method on the canvas element to get a new data URL, optionally specifying
the image type and quality of the new image.
Below is an example of how to implement this and some widgets to try it yourself.