先看看效果(采用react实现,其他框架实现也是一样的)
如上,我们可以剪裁任意的图片得到一个剪裁后的base64编码的图片
实现(react)
1.安装
npm i react-cropper -S
2.引入
import Cropper from "react-cropper";//引入组件库
import "cropperjs/dist/cropper.css";//引入相应的样式
3.核心代码
逻辑层
constructor() {
super();
this.state = {
img: "",
};
this.cropper = "";
}
cropImage = () => {
this.setState({
img: this.cropper.cropper.getCroppedCanvas().toDataURL(),
});
};
界面层
render() {
const { img } = this.state;
return (
<div>
<div style={{ width: "100%" }}>
<Cropper
src={logo}
ref={(cropper) => {
this.cropper = cropper;
}}
style={{ height: 400, width: "100%" }}
aspectRatio={1 / 1}
guides={true}
/>
</div>
<div>
<Button
type="primary"
onClick={this.cropImage}
style={{ marginTop: "10px" }}
>
确认裁剪
</Button>
</div>
<div style={{ textAlign: "center" }}>
{img ? (
<div>
<p>剪裁后的图片</p>
<img
style={{
width: "100px",
height: "100px",
marginTop: "32px",
border: "1px solid #a1a1a1",
padding: "4px",
}}
src={img}
alt="图片"
/>
</div>
) : null}
</div>
</div>
)}
完整代码
import React from "react";
import logo from "./logo512.png";//注意引用路径
import { Button } from "antd-mobile";
import Cropper from "react-cropper";
import "cropperjs/dist/cropper.css";
export default class ReduxDemo extends React.Component {
constructor() {
super();
this.state = {
img: "",
};
this.cropper = "";
}
cropImage = () => {
this.setState({
img: this.cropper.cropper.getCroppedCanvas().toDataURL(),
});
};
render() {
const { img } = this.state;
return (
<div>
<div style={{ width: "100%" }}>
<Cropper
src={logo}
ref={(cropper) => {
this.cropper = cropper;
}}
style={{ height: 400, width: "100%" }}
aspectRatio={1 / 1}
guides={true}
/>
</div>
<div>
<Button
type="primary"
onClick={this.cropImage}
style={{ marginTop: "10px" }}
>
确认裁剪
</Button>
</div>
<div style={{ textAlign: "center" }}>
{img ? (
<div>
<p>剪裁后的图片</p>
<img
style={{
width: "100px",
height: "100px",
marginTop: "32px",
border: "1px solid #a1a1a1",
padding: "4px",
}}
src={img}
alt="图片"
/>
</div>
) : null}
</div>
</div>
)}
}
相关链接
npm:点击这里