如何为react-cropper设置固定裁剪框宽高
如何为react-cropper设置固定尺寸的裁剪框
要实现固定宽高(比如200px×300px)的裁剪框,你需要结合cropper实例的API和组件属性来锁定尺寸,具体修改如下:
- 锁定裁剪比例:设置
aspectRatio为目标宽高比(200/300 = 2/3),确保裁剪框始终保持这个比例 - 设置固定尺寸:在
onInitialized回调中调用setCropBoxData方法,直接指定裁剪框的宽高和位置 - 禁用调整功能:添加
cropBoxResizable={false},禁止用户拖动调整裁剪框大小
修改后的完整代码:
import React, { useState } from "react"; import Cropper from "react-cropper"; import "cropperjs/dist/cropper.css"; import "./Demo.css"; type Props = { LabelName?: string; }; export const Demo = (props:Props) => { const {LabelName} = props; const [image, setImage] = useState(""); const [cropData, setCropData] = useState("#"); const [cropper, setCropper] = useState<any>(); const onChange = (e: any) => { e.preventDefault(); let files; if (e.dataTransfer) { files = e.dataTransfer.files; } else if (e.target) { files = e.target.files; } const reader = new FileReader(); reader.onload = () => { setImage(reader.result as any); }; reader.readAsDataURL(files[0]); }; const getCropData = () => { if (typeof cropper !== "undefined") { setCropData(cropper.getCroppedCanvas().toDataURL()); } }; return ( <div> <div style={{ width: "100%" }}> <input type="file" onChange={onChange} /> <br /> <Cropper zoomTo={0.5} preview=".img-preview" src={image} viewMode={1} background={false} responsive={true} checkOrientation={false} // 设置裁剪比例为2:3(对应宽200,高300) aspectRatio={2/3} // 禁用裁剪框大小调整 cropBoxResizable={false} onInitialized={(instance) => { setCropper(instance); // 初始化时设置裁剪框固定尺寸和居中位置 const containerData = instance.getContainerData(); instance.setCropBoxData({ width: 200, height: 300, left: (containerData.width - 200) / 2, top: (containerData.height - 300) / 2 }); }} guides={true} /> </div> <br style={{ clear: "both" }} /> {/* 可选:添加预览区域和裁剪按钮 */} <div className="img-preview" style={{ width: 200, height: 300, overflow: 'hidden', marginTop: '10px' }}></div> <button onClick={getCropData} style={{ marginTop: '10px' }}>获取裁剪后的图片</button> {cropData !== "#" && <img src={cropData} alt="裁剪后" style={{ marginTop: '10px' }} />} </div> ); }; export default Demo;
关键修改说明:
- aspectRatio={2/3}:锁定裁剪框的宽高比例,确保即使拖动裁剪框改变位置,比例也不会偏移
- cropBoxResizable={false}:彻底禁止用户通过拖动边缘调整裁剪框大小
- onInitialized中的setCropBoxData:组件初始化完成后,直接设置裁剪框的固定宽高,并通过容器尺寸计算让裁剪框居中显示
- 移除了
initialAspectRatio和autoCropArea,因为我们不需要自动填充的裁剪框,而是自定义固定尺寸
这样设置后,裁剪框会保持200px×300px的固定大小,用户仅能拖动裁剪框选择区域或缩放图片,无法修改裁剪框本身的尺寸。
内容的提问来源于stack exchange,提问作者user15361826
相关产品推荐
相关产品推荐

