简体   繁体   English

如何在不拉伸的情况下将图像缩放到KonvaJS画布?

[英]How to scale image to KonvaJS canvas without stretching?

I'm trying to show images with different aspect ratios on 1080x1920 canvas. 我试图在1080x1920画布上显示不同宽高比的图像。 So when I try to show 9:16 images, it scales perfectly, but if aspect ratio is 4:3 or 3:4, scaled image stretches. 因此,当我尝试显示9:16图像时,它会完美缩放,但如果纵横比为4:3或3:4,则缩放图像会延伸。

What I want to do is, if aspect ratio is 3:4, scaling and showing image as 9:16 on center and cutting edges. 我想要做的是,如果纵横比为3:4,缩放并在中心和切割边缘显示图像为9:16。 (So if original width is 1440, showing only 1080 and leaving 180px at each side off the screen. And if original width is 3024, scaling it down to 1440 and then cut) (因此,如果原始宽度为1440,则仅显示1080并在屏幕两侧留下180px。如果原始宽度为3024,则将其缩小至1440然后切割)

And if image is not portrait but landscape, showing it on center and filling remaining space with some color. 如果图像不是肖像而是风景,将其显示在中心并用一些颜色填充剩余空间。

How can I achive this? 我怎么能得到这个? Does KonvaJS provides easy way to do this? KonvaJS提供了简单的方法吗?

No konvaJS does not provide a way around that, you need to use your own logic for positioning the image at the center for different resolutions. 没有konvaJS没有提供解决方法,您需要使用自己的逻辑将图像定位在中心以获得不同的分辨率。

I have used logic for finding the image resolution which fits the provided dimensions in my personal project. 我使用逻辑来查找符合我个人项目中提供的尺寸的图像分辨率。 Check if it helps. 检查它是否有帮助。

function getScaledImageCoordinates(
    containerWidth,
    containerHeigh,
    widt,
    height,
) {
    var widthRatio = (containerWidth) / width,
        heightRatio = (containerHeight) / height
    var bestRatio = Math.min(widthRatio, heightRatio)
    var newWidth = width * bestRatio,
        newHeight = height * bestRatio
    return {newWidth, newHeight}
} 

You can find the image resolution that fits your container (say 1080x1920) and then center position the image on Konva Stage 您可以找到适合您容器的图像分辨率(例如1080x1920),然后将图像居中放置在Konva Stage上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM