首页 > 解决方案 > 如何将图像缩放和居中为方形尺寸?

问题描述

这些问题相似但无济于事:thisthisthisthis

目标是将图像绘制到方形画布上,同时保留原始纵横比并在原始纵横比不是正方形时使图像居中。

例如,使用附加的 1262x2688 图像。下面的代码将其大小调整为 100x100,但它会扭曲纵横比。

代码应: (1) 缩放图像以适合 100x100 画布;(2) 保持纵横比;(3) 在画布内垂直和水平居中图像。

    // Create canvas element.
    var canvas = $(document.createElement("canvas"));

    // Get canvas context.
    var context = canvas[0].getContext("2d");

    // Set canvas size.
    canvas[0].width = 100;
    canvas[0].height = 100;

    // Write image to canvas.
    context.drawImage(image, 0, 0, newWidth, newHeight);

图片

在此处输入图像描述

标签: javascriptimagecanvashtml5-canvasresize

解决方案


要在保留方面的同时将图像适合画布,请使用以下内容

const w = image.naturalWidth;
const h = image.naturalHeight;

// Get the min scale to fit the image to the canvas
const scale = Math.min(canvas.width / w, canvas.height / h);

// Set the transform to scale the image, and center to the canvas
ctx.setTransform(scale, 0, 0, scale, canvas.width / 2, canvas.height / 2);

// draw the image offset by half its width and height to center and fit
ctx.drawImage(image, -w / 2, -h / 2, w, h);

// to reset the transform
// ctx.setTransform(1,0,0,1,0,0);

推荐阅读