Solving border-radius + overflow: hidden problem with canvas

I faced the following task:


There is a block with a background (not necessarily homogeneous), in it there are a certain number of round elements with a white background, inside which rounded pictures of any size are placed. If the image size is smaller than the block size, it is centered (both vertically and horizontally); if the image size is larger than the block size, the larger parameter of the image occupies 100% of the block parameter, and the second parameter retains a proportional ratio, as in the original image.

For many, it is no secret that if you round off the picture itself, it will turn out beautifully, only with a picture whose aspect ratio is 1: 1, in other cases there will be problems:


Using standard css properties (border-radius: 150px; overflow: hidden;), as applied to a block with a picture, does not work in many link browsers (until the article came out - old) . You can find many different solutions to the problem, but not one of them suited me. I propose the following solution (it is not universal, including it does not work in IE7, IE8 ) but I find it useful and it works in all browsers that support canvas. Center the pictures vertically:


	$(this).find('img').css('margin-top', parseInt(-$(this).find('img').height()/2));

Replace the picture with canvas

var i=0, mywidth, myheight;		
    var contWidth = $(this).width(),
        contHeight = $(this).height(), //получаем значение ширины и высоты контейнера
        cnv = document.createElement("canvas"); //создаем канву
    cnv.height=contHeight;	//задаем ей значения высоты и ширины такие как у контейнера				
    $(this).prepend(cnv); //добавляем в начало контейнера канву, картинка при этом просто уезжает вниз
    var j=i-1;
    $(this).find('canvas').attr('id', 'canvas'+j); //даем канве свой id
    var ctx = document.getElementById('canvas'+j).getContext('2d'), //инициализируем контекст
        img = new Image(), //создаем в канве картинку
        attrsrc=$(this).find('img').attr('src'); //получаем путь исходной картинки
    img.src = attrsrc; //присваиваем картинке в канве путь исходной картинки				
    img.onload = function(){
        mywidth = $('#canvas'+j).next('img').width();
        myheight = $('#canvas'+j).next('img').height(); //получаем высоту и ширину исходной картинки
        var xpos = (contWidth-mywidth)/2, 
        ypos = (contHeight-myheight)/2; //рассчитываем расположение картинки в канве
        ctx.drawImage(img, xpos, ypos, mywidth, myheight);	//рисуем картинку на холст

Then just round off the canvas:

.i-img-cont canvas{border-radius:150px;}

You can also specify browsers in which you do not need to create a canvas (e.g. FF, IE9-10, Chrome). Or those in which it is necessary so as not to do too much work for smart browsers.

PS Excanvas does not help, if there are solutions for IE7-8, except for cutting corners in Photoshop, I will be grateful.

Also popular now: