javascript - Cropper.js,用居中的图像填充 div
问题描述
我修改了cropper.js 库网站(https://fengyuanchen.github.io/cropperjs/)中的示例。
本示例原版:https ://fengyuanchen.github.io/cropperjs/examples/fixed-crop-box.html
我的版本:https ://codepen.io/reti/pen/ExmyyaX
var image1
var cropper1
var image2
var cropper2
function cropperInstances() {
image1 = document.querySelector('#image1');
cropper1 = new Cropper(image1, {
dragMode: 'move',
aspectRatio: 1 / 1,
restore: false,
guides: false,
center: true,
highlight: false,
cropBoxMovable: false,
cropBoxResizable: false,
toggleDragModeOnDblclick: false,
minCropBoxWidth: 300,
minCropBoxHeight: 300,
});
image2 = document.querySelector('#image2');
cropper2 = new Cropper(image2, {
dragMode: 'move',
aspectRatio: 1 / 1,
restore: false,
guides: false,
center: true,
highlight: false,
cropBoxMovable: false,
cropBoxResizable: false,
toggleDragModeOnDblclick: false,
minCropBoxWidth: 300,
minCropBoxHeight: 300,
});
}
window.addEventListener('DOMContentLoaded', cropperInstances);
.container {
margin: 100px auto;
width: 300px;
height: 300px;
}
img {
max-width: 100%;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cropper.js</title>
<link rel="stylesheet"
href="https://srv19859.microhost.com.pl/cropper/css/cropper.css">
</head>
<body>
<div class="container">
<img id="image1"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/1200px-Lion_waiting_in_Namibia.jpg">
</div>
<div class="container">
<img id="image2"
src="https://upload.wikimedia.org/wikipedia/de/9/93/Burj_Khalifa.jpg">
</div>
<script
src="https://srv19859.microhost.com.pl/cropper/js/cropper.js"></script>
</body>
</html>
我希望这些图像在上传时能够填充它们的 div,但要使它们垂直和水平居中,但是:
- 如果图像具有水平方向,则其高度不能高于 div
- 如果图像有垂直方向,那么它的宽度不能大于 div。
就像这里一样:https ://ibb.co/Twqxy2h
怎么做?我正在尝试不同的方法,但我已经没有想法了。
问题与这篇文章完全相同:Panzoom library and fill a div with a centered image
解决方案
我想我已经解决了这个问题:
function fillCropContainer() {
var instanceArray = [cropper1, cropper2]
var ratio
instanceArray.forEach((el) => {
var imgNatHeight = el.imageData.naturalHeight
var imgNatWidth = el.imageData.naturalWidth
if (imgNatHeight < imgNatWidth) {
ratio = 300 / imgNatHeight
el.zoomTo(ratio)
} else {
ratio = 300 / imgNatWidth
el.zoomTo(ratio)
}
})
}
推荐阅读
- react-native - 如何删除顶部标签栏下不必要的空格?
- angularjs - 滚动到底部时如何触发功能
- sql - 获取日期范围内不连续的行
- json - 如何将 JSON 数组值传递到 Jasper Reports 子报表中?
- reporting-services - 创建一个表达式来添加和减去两个独立查找表达式的值
- tensorflow - 为什么在我使用 XLA_FLAGS 转储 ptx 和 llvm 时没有为矩阵乘法张量流操作生成 PTX?
- android - 有没有办法阻止我的应用在特定时间范围内发送通知?
- google-cloud-platform - 托管简单节点服务器和网站的最便宜方式,在 Google Cloud Platform 上的每日浏览量很少
- javascript - 配置json数据有问题,有点卡住
- snakemake - 尝试为工作流创建目录时发生 ChildIOException [Snakemake]