Frontend Development 10 min read

JavaScript Image Compression Using Canvas and Vue

This article provides a step‑by‑step tutorial on implementing client‑side image compression in JavaScript with the Canvas API, including a complete Vue component, detailed API explanations, handling of file input, canvas drawing, base64 conversion, and cross‑browser download techniques.

政采云技术
政采云技术
政采云技术
JavaScript Image Compression Using Canvas and Vue

Introduction: The article explains how to implement image compression directly in JavaScript using the Canvas API, providing a Vue component example.

Compression approach: It outlines steps – obtain the uploaded file, convert it to a base64 string via FileReader, draw the image onto a canvas, adjust resolution or quality, and export the result.

Pros and cons: Canvas compression is simple and configurable, but only JPEG/WebP support quality adjustment; other formats rely on resizing.

Code implementation: The Vue component includes a template with an <input type="file" id="input-img" @change="compress" /> for uploading, an <a :download="fileName" :href="compressImg">普通下载</a> for download, and a canvas rendering section. The script defines methods compress() , handleCompressImage(img, type) , and downloadImg() that handle file reading, image loading, canvas drawing using drawImage , converting to base64 with canvas.toDataURL(`image/${type}`) , and downloading either via the download attribute or IE‑specific window.navigator.msSaveOrOpenBlob .

API details: Explanations of drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) parameters, toDataURL(type, encoderOptions) options, and the conversion of base64 data to a Blob using window.atob and Uint8Array for cross‑browser compatibility.

Conclusion: The guide provides a practical solution for front‑end image compression, suitable for reducing upload size, adding editing features, and handling downloads across modern browsers and IE.

FrontendJavaScriptCanvasimage compressionVue
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.