Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent background-image from scaling when user zooms in or out

I have this transparent raster-like background-overlay: link to image <-- try zooming out your browser to see the effect

When zooming in or out (especially on mobile devices this happens a lot) the image tends to look smudgy and ugly. Is there a way to have this background-image always be 10 x 10 pixels in size on the screen no matter how the page is zoomed, so it always looks sharp?

Doing some searches I found that this might be a hard task. In case it is impossible: is there a way to alter the zooming filters in a way the image looks better when zoomed out or in?

like image 712
kapoko Avatar asked Oct 08 '12 11:10

kapoko


1 Answers

On Hi-Res display, like mobile devices' display, you will always have the blurry effect because of the high pixels density due to the high resolution on a small size screen.

There is a workaround to fix this:

  • Create a double sized background image: your image is 10px 10px, create a 20px 20px one instead.

  • Apply the background image using the desired size: background-size: 10px 10px;

With this trick, when zooming in or viewing the image on Hi-Res display the image will not appears blurry anymore.

As requested in comments, here is the code to adapt the background size to the zoom:

JAVASCRIPT :

if (window.addEventListener){           
    window.addEventListener('resize', setBackground, false);
} else {
    window.attachEvent('onresize', setBackground);
}

function setBackground(){
    document.body.style.backgroundSize =
        (((( window.screen.width / ( window.screen.width / getImageWidth() )) / 10) > 1 ) ? (( window.screen.width / ( window.screen.width / getImageWidth() )) / 10) : 1) + "%";
}

function getImageWidth(){

    var imageSrc = document
                    .body
                     .style
                      .backgroundImage
                       .replace(/url\((['"])(.*?)\1\)/gi, '$2')
                        .split(',')[0];

    var image = new Image();
    image.src = imageSrc;

    var width = image.width;

    return width;

}       

HTML:

<body onLoad="javascript:setBackground();" style="background: url(bkg.jpg) repeat;">
like image 103
Cirou Avatar answered Nov 14 '22 22:11

Cirou