The HTML <canvas> element is one of the most powerful and underused APIs in the browser. For image processing specifically, it gives you GPU-accelerated pixel manipulation with no external dependencies.
Here's exactly how EazyStudio uses Canvas to resize, compress, and convert images — all in-browser.
Reading an image into Canvas
The starting point is always the same: create an Image object, load the file, and draw it onto a Canvas.
function loadImageToCanvas(file) {
return new Promise((resolve) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
canvas.getContext('2d').drawImage(img, 0, 0);
URL.revokeObjectURL(url); // free memory
resolve(canvas);
};
img.src = url;
});
}
Resizing
Resizing is just changing the canvas dimensions before drawing. The browser's 2D context handles the interpolation.
function resizeImage(canvas, targetWidth, targetHeight) {
const resized = document.createElement('canvas');
resized.width = targetWidth;
resized.height = targetHeight;
const ctx = resized.getContext('2d');
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high'; // Lanczos-like
ctx.drawImage(canvas, 0, 0, targetWidth, targetHeight);
return resized;
}
Compression via quality parameter
Canvas's toBlob and toDataURL methods accept a quality parameter for JPEG and WebP output. This controls the JPEG compression ratio.
function compressToBlob(canvas, quality = 0.82) {
return new Promise((resolve) => {
canvas.toBlob(
(blob) => resolve(blob),
'image/jpeg',
quality // 0.0 (worst) to 1.0 (best)
);
});
}
Format conversion
Changing the MIME type in toBlob converts the format. PNG to WebP is literally one character change.
// PNG → WebP
canvas.toBlob(callback, 'image/webp', 0.9);
// JPG → PNG (lossless)
canvas.toBlob(callback, 'image/png');