Abdul Sadik Yalcin
Abdul Sadik Yalcin

Reputation: 1822

Prevent pixel decimals when using transform scale

I have a slider which consists of iframes that are 1366px x 768px which I scale to fit on window resize. However, when 1366 is divided I can randomly get decimals on the actual width of the element which causes what I call as 'pixel breaking'.

Notice the while line on the second image. This is actually the second slide which is my problem. Example; 1366px becomes 1045.234234px so they don't line up properly.

I know I can also add a width by removing the decimals as parseInt(scaleAmount * 1366) but I don't think that can always be accurate with different resolutions.

Anything I can try to resolve or minimise this?

Non-scaled version

scaled

var $el = $(element);
var elHeight = 768;
var elWidth = 1366;
var $wrapper = $(parent);

function doResize(event, ui) {
    var scale, origin;

    scale = Math.min(
        ui.size.width / elWidth,
        ui.size.height / elHeight
    );

    $el.css({
        'transform': "scale(" + scale + ")",
        '-webkit-transform': "scale(" + scale + ")"
    });
}

Upvotes: 1

Views: 1037

Answers (2)

Abdul Sadik Yalcin
Abdul Sadik Yalcin

Reputation: 1822

OK I think I've resolved it. I convert the transform scale to pixel value. Round up the pixel. And finally, convert the rounded pixel back to a transform scale. So the scaled pixel will always be an even number so therefore the pixels would not break anymore.

scale = Math.min(
    ui.size.width / elWidth,
    ui.size.height / elHeight
);

var scaleInPixels = scale * elWidth;
var evenPixel = 2 * Math.round(scaleInPixels / 2);
var finalScale = evenPixel / elWidth;

Upvotes: 1

aclave1
aclave1

Reputation: 1711

Since you're converting to a string, you can just trim off the decimal part of the number using scale.toFixed(0).

Upvotes: 1

Related Questions