she hates me
she hates me

Reputation: 1272

How to scale image to KonvaJS canvas without stretching?

I'm trying to show images with different aspect ratios on 1080x1920 canvas. 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.

What I want to do is, if aspect ratio is 3:4, scaling and showing image as 9:16 on center and cutting edges. (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)

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?

Upvotes: 0

Views: 3621

Answers (1)

Sarthak
Sarthak

Reputation: 183

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.

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,
    width,
    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

Upvotes: 3

Related Questions