Canvas Image Compression Guide

The use of the drawImage method in Canvas can be used to compress images. Below is a simple example code:

// 获取原始的图片对象
var img = new Image();
img.src = '原始图片路径';

// 创建一个Canvas元素
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');

// 设置Canvas的大小为压缩后的尺寸
var maxWidth = 200;
var maxHeight = 200;
var ratio = 1;
if (img.width > maxWidth || img.height > maxHeight) {
  ratio = Math.min(maxWidth / img.width, maxHeight / img.height);
}

canvas.width = img.width * ratio;
canvas.height = img.height * ratio;

// 在Canvas上绘制压缩后的图片
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

// 将Canvas转换为压缩后的图片数据
var compressedImage = canvas.toDataURL('image/jpeg', 0.7);

// 将压缩后的图片显示在页面上
var compressedImgElement = document.createElement('img');
compressedImgElement.src = compressedImage;
document.body.appendChild(compressedImgElement);

In the code above, an original image object is first created, followed by the creation of a Canvas element with a size set to the compressed dimensions. The drawImage method is then used to draw the compressed image on the Canvas, before converting the Canvas to compressed image data and displaying it on the page.

bannerAds