你的位置:首页 > 网页设计

[网页设计]手机不定大小头像处理


要求:

图像尺寸可能有以下几种可能:宽>高,宽<高,宽=高要求:最小的 宽/高 撑满盒子

1.CSS background实现

HTML

<h2>1. CSS3 background实现</h2><div class="m-box box-background box-background-w"></div><div class="m-box box-background box-background-h"></div><div class="m-box box-background box-background-wh"></div>

CSS

/* 假设你已经拥有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 center;  background-repeat: no-repeat;}

 


如图: 

 

2.JS实现并裁切

HTML

<!-- 假设你已经拥有DEMO里需要的图片 --><h2>2. JS实现</h2><div class="m-box"><img class="J_CropImage" src="img/400x200.jpg" alt=""/></div><div class="m-box"><img class="J_CropImage" src="img/200x400.jpg" alt=""/></div><div class="m-box"><img class="J_CropImage" src="img/400x400.jpg" alt=""/></div><canvas id="canvas" width="100" height="100"></canvas><div id="after"></div>

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_CropImage');for(var len = aImg.length - 1; len >= 0; len--){  loadImg(aImg[len], aImg[len].getAttribute('src'));}function getById(id){  return document.getElementById(id);}// 加载图片function loadImg(obj, src){  var img = new Image();  img.src = src;  img.onload = function(){    setImg(obj, img);  };}// 设置图片位置function setImg(o, img){  var width = img.width, height = img.height,      sx = 0, sy = 0, sw = 0, sh = 0, x = 0, y = 0, w = 100, h = 100;  if(width > height){    // 设置高度100%,改变宽度    o.style.cssText = 'height: 100%; margin-left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%);';    sx = (width - height)/2;    sh = sw = height;  }  else if(height > width){    // 设置宽度100%,改变高度    o.style.cssText = 'width: 100%; margin-top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%);';    sy = (height - width)/2;    sh = sw = width;  }  else{    // 相等,设置宽高100%    o.style.cssText = 'width: 100%; height: 100%;';    sh = sw = height;  }  cropImage(img.src, sx, sy, sw, sh, x, y, w, h);}// 图片裁切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);  };}

如图: