What is the HTML Canvas API?
The HTML Canvas API is a browser feature for drawing and manipulating pixel graphics with JavaScript, and it is what lets web apps trim, resize and convert images locally.
By Rocco Bombardieri · Updated
Explained in more detail
A canvas is an HTML element, <canvas>, that provides a bitmap you can draw on with JavaScript. The 2D drawing context offers shapes, text, and drawImage, which paints an image onto the canvas at any position and scale. Together these let a web page decode an image, change it and re-encode it without any server.
For image processing, three calls matter. drawImage places a decoded image on the canvas, scaling it with the smoothing settings. getImageData returns the pixels as an ImageData object whose data is a Uint8ClampedArray of red, green, blue and alpha bytes in sequence, which code can loop over to find a bounding box or change alpha. toBlob encodes the canvas back into a file, as PNG by default, or JPEG or WebP with a quality value from 0 to 1. If the browser cannot encode the requested type, it falls back to PNG.
There are caveats. Because of conversion to and from premultiplied alpha, the HTML Standard warns that pixels written with putImageData that are not fully opaque may read back with different values. Images loaded from another origin without permission taint the canvas, after which reading pixels throws a security error. Very large canvases hit browser or device size limits, and the limits differ across browsers.
Canvas output is a fresh re-encode. The canvas API gives you no way to carry EXIF or embedded color profiles from the source into the exported file, so expect them to be absent.
All of Triim's tools are built on it, which is why they run entirely in the browser.