【发布时间】:2019-08-31 16:46:50
【问题描述】:
我需要显示上传图片中的圆形头像。 如果用户上传方形图片(宽度等于高度),那么没有问题。
如果我知道宽度比高度长或更短,我就能解决问题。
但实际上,我不知道它和我无法使用 jquery 的问题。
我在用react.js,目前状态是这样的;
我在宽度较长的时候做了一个代码,因为宽度通常比高度长。
【问题讨论】:
我需要显示上传图片中的圆形头像。 如果用户上传方形图片(宽度等于高度),那么没有问题。
如果我知道宽度比高度长或更短,我就能解决问题。
但实际上,我不知道它和我无法使用 jquery 的问题。
我在用react.js,目前状态是这样的;
我在宽度较长的时候做了一个代码,因为宽度通常比高度长。
【问题讨论】:
有很多方法可以解决这个问题。最简单的方法是通过 CSS 将图像扩展到元素的边界,同时保持其纵横比。
或
您可以使用前端验证限制用户仅上传特定维度的图像,或通过Cloudinary 等 API 服务根据您的喜好处理图像,然后使用它。
使用 CSS
img{
width: 200px;
height: 200px;
object-fit:cover; /*this property does the magic*/
border-radius:50%;
}
.avatar{
width: 200px;
height: 200px;
background: url("https://www.milesanthonysmith.com/uploads/1/4/0/0/14006904/anchor-beard-style-1_orig.png") center center;
background-size:cover; /*this property does the magic*/
border-radius:50%;
}
<!--using in a image element-->
<img src="https://www.milesanthonysmith.com/uploads/1/4/0/0/14006904/anchor-beard-style-1_orig.png" alt="">
<!--using in a div-->
<div class="avatar"></div>
希望这会有所帮助!
【讨论】:
您可以在纯 JavaScript 中通过简单地检查图像的高度和宽度来做到这一点。简单例子:
var img = document.getElementById("profile-picture");
if(img.height === img.width){
console.log("Height and width are equal");
} else if (img.height > img.width) {
console.log("Height is greater than width");
} else {
console.log("Width is greater than height");
}
<img id="profile-picture" src="https://image.shutterstock.com/z/stock-photo-picture-of-smiling-handsome-businessman-in-office-265383200.jpg" />
【讨论】: