JavaScript中的文件

裁剪图片

原理:借助Canvas, 绘制圆形路径,裁剪,填充图片

/**
 * @description: 裁剪图片变为圆形
 * @return {Promise}
 * @param {String} url:普通路径
 */
export const clipImageUrl = (url) => {
    return new Promise((resolve, reject) => {
        let image = new Image();
        image.onload = function () {
            let width = image.width;
            let height = image.height;
            const minLength = Math.min(width, height);
            let canvas = document.createElement("canvas");
            let ctx = canvas.getContext("2d");
            canvas.width = minLength;
            canvas.height = minLength;
            // 计算图片绘制区域,确保图片保持比例
            const aspectRatio = image.width / image.height;
            let drawWidth, drawHeight;
            let offsetX = 0, offsetY = 0;

            if (aspectRatio > 1) {
                // 图片更宽
                drawHeight = canvas.height;
                drawWidth = drawHeight * aspectRatio;
                offsetX = (canvas.width - drawWidth) / 2;
            } else {
                // 图片更高
                drawWidth = canvas.width;
                drawHeight = drawWidth / aspectRatio;
                offsetY = (canvas.height - drawHeight) / 2;
            }

            // 将画布剪裁为圆形区域
            ctx.beginPath();
            ctx.arc(canvas.width / 2, canvas.height / 2, canvas.width / 2, 0, Math.PI * 2);
            ctx.closePath();
			// 剪切,【一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内(不能访问画布上的其他区域)】
            ctx.clip();

            // 在剪裁后的圆形区域内绘制图片
            ctx.drawImage(image, offsetX, offsetY, drawWidth, drawHeight);
            let newImage = new Image();
            newImage.src = canvas.toDataURL('image/png')
            return resolve(newImage.src);
        }
        image.src = url;
    })
}
posted @ 2024-10-23 16:46  拉布拉多~  阅读(4)  评论(0编辑  收藏  举报