refactor:简化头像计算,新增头像最大尺寸参数,避免头像裁剪出来太大

pull/199/head
youxia 3 years ago
parent 558bb35d70
commit 27704cd5f7

@ -85,36 +85,28 @@ function getCroppedImg(
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
if (!_isNil(ctx)) { if (!_isNil(ctx)) {
const maxSize = Math.max(image.width, image.height); // 设置头像大小
const safeArea = 2 * ((maxSize / 2) * Math.sqrt(2)); const size = 256;
// set each dimensions to double largest dimension to allow for a safe area for the canvas.width = size;
// image to rotate in without being clipped by canvas context canvas.height = size;
canvas.width = safeArea;
canvas.height = safeArea;
// translate canvas context to a central location on image to allow rotating around the center. // translate canvas context to a central location on image to allow rotating around the center.
ctx.translate(safeArea / 2, safeArea / 2); ctx.translate(size / 2, size / 2);
ctx.rotate(getRadianAngle(rotation)); ctx.rotate(getRadianAngle(rotation));
ctx.translate(-safeArea / 2, -safeArea / 2); ctx.translate(-size / 2, -size / 2);
// draw rotated image and store data. // draw rotated image and store data.
ctx.drawImage( ctx.drawImage(
image, image,
safeArea / 2 - image.width * 0.5, crop.x,
safeArea / 2 - image.height * 0.5 crop.y,
); crop.width,
const data = ctx.getImageData(0, 0, safeArea, safeArea); crop.height,
0,
// set canvas width to final desired crop size - this will clear existing context 0,
canvas.width = crop.width; size,
canvas.height = crop.height; size
// paste generated rotate image with correct offsets for x,y crop values.
ctx.putImageData(
data,
Math.round(0 - safeArea / 2 + image.width * 0.5 - crop.x),
Math.round(0 - safeArea / 2 + image.height * 0.5 - crop.y)
); );
} }

Loading…
Cancel
Save