📜 ⬆️ ⬇️

Solving the border-radius + overflow: hidden problem with canvas

I had the following task:

image

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

For many, it is no secret that if you round out the picture itself, it will turn out beautifully, only with a picture, the aspect ratio of which is 1: 1, in other cases problems will arise:
')
image

The use of standard css properties (border-radius: 150px; overflow: hidden;), as applied to the block with a picture, does not work in many (as long as the article is published - old) browsers link .

image

You can find many different solutions to the problem, but not one of them came up to 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.

jsfiddle.net/iLight/EsFTG/23

We center the pictures vertically:

$('.i-img-cont').each(function(){ $(this).find('img').css('margin-top', parseInt(-$(this).find('img').height()/2)); }); 

Replace the image on canvas

 var i=0, mywidth, myheight; $('.i-img-cont').each(function(){ var contWidth = $(this).width(), contHeight = $(this).height(), //      cnv = document.createElement("canvas"); //  cnv.width=contWidth; cnv.height=contHeight; //          $(this).prepend(cnv); //    ,       i++; 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 the canvas:

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

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

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

Source: https://habr.com/ru/post/179525/


All Articles