首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将图像缩放和居中到正方形尺寸?

如何将图像缩放和居中到正方形尺寸?
EN

Stack Overflow用户
提问于 2019-10-08 08:07:02
回答 3查看 814关注 0票数 1

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

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

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

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

代码语言:javascript
运行
复制
    // 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);

图像

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-10-13 08:40:32

下面是我们使用的代码:

代码语言:javascript
运行
复制
    // 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);
票数 1
EN

Stack Overflow用户

发布于 2019-10-08 17:53:31

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

代码语言:javascript
运行
复制
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);
票数 1
EN

Stack Overflow用户

发布于 2019-10-08 08:39:29

假设我得到了正确的计算方法,下面的方法可能行得通?

代码语言:javascript
运行
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58278575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档