Handle mobile phone pictures of an indefinite size and mobile phone pictures
Requirements:
Image size may have the following possibilities: width> height, width 1. CSS background implementation
HTML
<H2> 1. CSS3 background implementation
CSS
/* Assume that you already have the image required in the DEMO */. m-box {width: 100px; height: 100px; border-radius: 50%; overflow: hidden; margin-bottom: 20px ;}. box-background-w {background-image: url (img/400x200.jpg );}. box-background-h {background-image: url (img/200x400.jpg );}. box-background-wh {background-image: url (img/400x400.jpg );}. box-background {-webkit-background-size: cover; background-position: center; background-repeat: no-repeat ;}
2. JS implementation and cropping
HTML
<! -- Assume that you already have the image needed in the DEMO -->
CSS
.m-box { width: 100px; height: 100px; border-radius: 50%; overflow: hidden; margin-bottom: 20px;}#after { padding: 10px; }#after img { margin: 10px; }
JS
// Usevar aImg = document. getElementsByClassName ('J _ cropimag'); for (var len = aImg. length-1; len> = 0; len --) {loadImg (aImg [len], aImg [len]. getAttribute ('src');} function getById (id) {return document. getElementById (id);} // load the Image function loadImg (obj, src) {var img = new Image (); img. src = src; img. onload = function () {setImg (obj, img) ;}}// set the image position function setImg (o, img) {var width = img. width, hei Ght = img. height, sx = 0, sy = 0, sw = 0, sh = 0, x = 0, y = 0, w = 100, h = 100; if (width> height) {// set the height to 100%, and change the width to o.style.css Text = 'height: 100%; margin-left: 50%;-webkit-transform: translateX (-50%); transform: translateX (-50%); '; sx = (width-height)/2; sh = sw = height;} else if (height> width) {// set the width to 100%, change the height of o.style.css Text = 'width: 100%; margin-top: 50%;-webkit-transform: transla TeY (-50%); transform: translateY (-50%); '; sy = (height-width)/2; sh = sw = width;} else {// equal, set the width and height to 100% o.style.css Text = 'width: 100%; height: 100%; '; sh = sw = height;} cropImage (img. src, sx, sy, sw, sh, x, y, w, h);} // image cropping function cropImage (src, sx, sy, sw, sh, x, y, w, h) {var oCanvas = getById ('canvas '); if (! OCanvas. getContext) return; var ctx = oCanvas. getContext ('2d '); var oImg = new Image (); oImg. src = src; oImg. onload = function () {ctx. drawImage (oImg, sx, sy, sw, sh, x, y, w, h); var resImg = document. createElement ('img '); resImg. src = oCanvas. toDataURL ('+ image/png +', 0.8); getById ('after '). appendChild (resImg );};}