Как масштабировать и центрировать изображение по квадратным размерам? - PullRequest
0 голосов
/ 08 октября 2019

Эти вопросы похожи, но не помогают: это , это , это и это .

Цель состоит в том, чтобы нарисовать изображение на квадратном холсте, сохранив исходное соотношение сторон и центрировав изображение, если исходное соотношение сторон не является квадратным.

Например, возьмите прилагаемое изображение 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);

Изображение

enter image description here

Ответы [ 3 ]

1 голос
/ 08 октября 2019

Чтобы разместить изображение на холсте, сохранив аспект, используйте следующее

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);
0 голосов
/ 13 октября 2019

Вот код, который мы использовали:

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

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

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

    // Set image size, must use image.naturalWidth and image.naturalHeight -- not image.width and image.height.
    const imageWidth = image.naturalWidth;
    const imageHeight = image.naturalHeight;

    // Set scale to fit image to canvas, 
    const scale = Math.min(canvasWidth/imageWidth, canvasHeight/imageHeight);

    // Set new image dimensions.
    const scaledWidth = imageWidth * scale;
    const scaledHeight = imageHeight * scale;

    // Draw image in center of canvas.
    context.drawImage(image, (canvasWidth - scaledWidth)/2, (canvasHeight - scaledHeight)/2, scaledWidth, scaledHeight);
0 голосов
/ 08 октября 2019

Предполагая, что вычисления выполнены правильно, может сработать следующее:

ratio = image.width/image.height;
if (image.width > image.height) {
    output.height = ( 100 / ratio ) 
    output.width = 100
    output.x = 0
    output.y = (100 - output.height) / 2
} else {
    output.height = 100
    output.width = 100 * ratio
    output.x = (100 - output.width) / 2
    output.y = 0
}
...