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:

  1. Once the image is uploaded, use the FileReader API to get the contents of the image as a data URL.
  2. Instantiate a new Image object and set its URL to the data URL obtained in step 1.
  3. Create a canvas element, but do not add it to the page.
  4. 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.
  5. 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.
  6. 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.