cl-cropper.uvue 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. <template>
  2. <view
  3. class="cl-cropper"
  4. :class="[pt.className]"
  5. @touchstart="onTouchStart"
  6. @touchmove.stop.prevent="onTouchMove"
  7. @touchend="onTouchEnd"
  8. @touchcancel="onTouchEnd"
  9. v-if="visible"
  10. >
  11. <!-- 图片容器 - 可拖拽和缩放的图片区域 -->
  12. <view class="cl-cropper__image">
  13. <image
  14. class="cl-cropper__image-inner"
  15. :class="[pt.image?.className]"
  16. :src="imageUrl"
  17. :style="imageStyle"
  18. @load="onImageLoaded"
  19. ></image>
  20. </view>
  21. <!-- 遮罩层 - 覆盖裁剪框外的区域 -->
  22. <view class="cl-cropper__mask" :class="[pt.mask?.className]">
  23. <view
  24. v-for="(item, index) in ['top', 'right', 'bottom', 'left']"
  25. :key="index"
  26. :class="`cl-cropper__mask-item cl-cropper__mask-item--${item}`"
  27. :style="maskStyle[item]!"
  28. ></view>
  29. </view>
  30. <!-- 裁剪框 - 可拖拽和调整大小的选择区域 -->
  31. <view class="cl-cropper__crop-box" :class="[pt.cropBox?.className]" :style="cropBoxStyle">
  32. <!-- 裁剪区域 - 内部可继续拖拽图片 -->
  33. <view class="cl-cropper__crop-area" :class="{ 'is-resizing': isResizing }">
  34. <!-- 九宫格辅助线 - 在调整大小时显示 -->
  35. <view
  36. class="cl-cropper__guide-lines"
  37. :class="{
  38. 'is-show': showGuideLines
  39. }"
  40. >
  41. <view class="cl-cropper__guide-line cl-cropper__guide-line--h1"></view>
  42. <view class="cl-cropper__guide-line cl-cropper__guide-line--h2"></view>
  43. <view class="cl-cropper__guide-line cl-cropper__guide-line--v1"></view>
  44. <view class="cl-cropper__guide-line cl-cropper__guide-line--v2"></view>
  45. <view class="cl-cropper__guide-text">
  46. <cl-text
  47. :pt="{
  48. className: '!text-xl'
  49. }"
  50. color="white"
  51. >
  52. {{ cropBox.width }}
  53. </cl-text>
  54. <cl-icon name="close-line" color="white"></cl-icon>
  55. <cl-text
  56. :pt="{
  57. className: '!text-xl'
  58. }"
  59. color="white"
  60. >
  61. {{ cropBox.height }}
  62. </cl-text>
  63. </view>
  64. </view>
  65. </view>
  66. <template v-if="resizable">
  67. <view
  68. v-for="item in ['tl', 'tr', 'bl', 'br']"
  69. :key="item"
  70. class="cl-cropper__drag-point"
  71. :class="[`cl-cropper__drag-point--${item}`]"
  72. @touchstart.stop="onResizeStart($event as TouchEvent, item)"
  73. >
  74. <view class="cl-cropper__corner-indicator"></view>
  75. </view>
  76. </template>
  77. </view>
  78. <!-- 底部按钮组 -->
  79. <view class="cl-cropper__op" :class="[pt.op?.className]" :style="opStyle" @touchmove.stop>
  80. <!-- 关闭 -->
  81. <view class="cl-cropper__op-item" :class="[pt.opItem?.className]">
  82. <cl-icon name="close-line" color="white" :size="50" @tap="close"></cl-icon>
  83. </view>
  84. <!-- 旋转 -->
  85. <view class="cl-cropper__op-item" :class="[pt.opItem?.className]">
  86. <cl-icon
  87. name="anticlockwise-line"
  88. color="white"
  89. :size="40"
  90. @tap="rotate90"
  91. ></cl-icon>
  92. </view>
  93. <!-- 重置 -->
  94. <view class="cl-cropper__op-item" :class="[pt.opItem?.className]">
  95. <cl-icon name="reset-right-line" color="white" :size="40" @tap="reset"></cl-icon>
  96. </view>
  97. <!-- 重新选择 -->
  98. <view class="cl-cropper__op-item" :class="[pt.opItem?.className]">
  99. <cl-icon name="image-line" color="white" :size="40" @tap="chooseImage"></cl-icon>
  100. </view>
  101. <!-- 确定 -->
  102. <view class="cl-cropper__op-item" :class="[pt.opItem?.className]">
  103. <cl-icon name="check-line" color="white" :size="50" @tap="toPng"></cl-icon>
  104. </view>
  105. </view>
  106. <!-- 裁剪用 -->
  107. <view class="cl-cropper__canvas">
  108. <canvas
  109. ref="canvasRef"
  110. :id="canvasId"
  111. :style="{
  112. height: `${cropBox.height}px`,
  113. width: `${cropBox.width}px`
  114. }"
  115. ></canvas>
  116. </view>
  117. </view>
  118. </template>
  119. <script setup lang="ts">
  120. import { computed, ref, reactive, nextTick, getCurrentInstance } from "vue";
  121. import type { PassThroughProps } from "../../types";
  122. import { canvasToPng, getDevicePixelRatio, getSafeAreaHeight, parsePt, uuid } from "@/cool";
  123. // 定义遮罩层样式类型
  124. type MaskStyle = {
  125. top: UTSJSONObject; // 上方遮罩样式
  126. right: UTSJSONObject; // 右侧遮罩样式
  127. bottom: UTSJSONObject; // 下方遮罩样式
  128. left: UTSJSONObject; // 左侧遮罩样式
  129. };
  130. // 定义图片信息类型
  131. type ImageInfo = {
  132. width: number; // 图片原始宽度
  133. height: number; // 图片原始高度
  134. isLoaded: boolean; // 图片是否已加载
  135. };
  136. // 定义图片变换类型
  137. type Transform = {
  138. translateX: number; // 水平位移
  139. translateY: number; // 垂直位移
  140. };
  141. // 定义尺寸类型
  142. type Size = {
  143. width: number; // 宽度
  144. height: number; // 高度
  145. };
  146. // 定义裁剪框类型
  147. type CropBox = {
  148. x: number; // 裁剪框 x 坐标
  149. y: number; // 裁剪框 y 坐标
  150. width: number; // 裁剪框宽度
  151. height: number; // 裁剪框高度
  152. };
  153. // 定义触摸状态类型
  154. type TouchState = {
  155. startX: number; // 触摸开始 x 坐标
  156. startY: number; // 触摸开始 y 坐标
  157. startDistance: number; // 双指触摸开始距离
  158. startImageWidth: number; // 触摸开始时图片宽度
  159. startImageHeight: number; // 触摸开始时图片高度
  160. startTranslateX: number; // 触摸开始时水平位移
  161. startTranslateY: number; // 触摸开始时垂直位移
  162. startCropBoxWidth: number; // 触摸开始时裁剪框宽度
  163. startCropBoxHeight: number; // 触摸开始时裁剪框高度
  164. isTouching: boolean; // 是否正在触摸
  165. mode: string; // 触摸模式:image/resizing
  166. direction: string; // 调整方向:tl/tr/bl/br
  167. };
  168. // 定义组件选项
  169. defineOptions({
  170. name: "cl-cropper" // 组件名称
  171. });
  172. // 定义组件属性
  173. const props = defineProps({
  174. // 透传样式配置对象
  175. pt: {
  176. type: Object,
  177. default: () => ({})
  178. },
  179. // 裁剪框初始宽度(像素)
  180. cropWidth: {
  181. type: Number,
  182. default: 300
  183. },
  184. // 裁剪框初始高度(像素)
  185. cropHeight: {
  186. type: Number,
  187. default: 300
  188. },
  189. // 图片最大缩放倍数
  190. maxScale: {
  191. type: Number,
  192. default: 3
  193. },
  194. // 是否可以自定义裁剪框大小
  195. resizable: {
  196. type: Boolean,
  197. default: false
  198. }
  199. });
  200. // 定义事件发射器
  201. const emit = defineEmits(["crop", "load", "error"]);
  202. // 获取当前实例
  203. const { proxy } = getCurrentInstance()!;
  204. // 创建唯一的canvas ID
  205. const canvasId = `cl-cropper__${uuid()}`;
  206. // 创建canvas实例
  207. const canvasRef = ref<UniElement | null>(null);
  208. // 像素取整工具函数 - 避免小数点造成的样式兼容问题
  209. function toPixel(value: number): number {
  210. return Math.round(value); // 四舍五入取整
  211. }
  212. // 定义透传样式配置类型
  213. type PassThrough = {
  214. className?: string; // 组件根元素类名
  215. image?: PassThroughProps; // 图片元素透传属性
  216. op?: PassThroughProps; // 底部按钮组透传属性
  217. opItem?: PassThroughProps; // 按钮透传属性
  218. mask?: PassThroughProps; // 遮罩层透传属性
  219. cropBox?: PassThroughProps; // 裁剪框透传属性
  220. };
  221. // 解析透传样式配置
  222. const pt = computed(() => parsePt<PassThrough>(props.pt));
  223. // 创建容器尺寸响应式对象
  224. const container = reactive<Size>({
  225. height: 0, // 获取视图高度
  226. width: 0 // 获取视图宽度
  227. });
  228. // 创建图片信息响应式对象
  229. const imageInfo = reactive<ImageInfo>({
  230. width: 0, // 初始宽度为 0
  231. height: 0, // 初始高度为 0
  232. isLoaded: false // 初始加载状态为未加载
  233. });
  234. // 创建图片变换响应式对象
  235. const transform = reactive<Transform>({
  236. translateX: 0, // 初始水平位移为 0
  237. translateY: 0 // 初始垂直位移为 0
  238. });
  239. // 创建图片尺寸响应式对象
  240. const imageSize = reactive<Size>({
  241. width: 0, // 初始显示宽度为 0
  242. height: 0 // 初始显示高度为 0
  243. });
  244. // 创建裁剪框响应式对象
  245. const cropBox = reactive<CropBox>({
  246. x: 0, // 初始 x 坐标为 0
  247. y: 0, // 初始 y 坐标为 0
  248. width: props.cropWidth, // 使用传入的裁剪框宽度
  249. height: props.cropHeight // 使用传入的裁剪框高度
  250. });
  251. // 创建触摸状态响应式对象
  252. const touch = reactive<TouchState>({
  253. startX: 0, // 初始触摸 x 坐标为 0
  254. startY: 0, // 初始触摸 y 坐标为 0
  255. startDistance: 0, // 初始双指距离为 0
  256. startImageWidth: 0, // 初始图片宽度为 0
  257. startImageHeight: 0, // 初始图片高度为 0
  258. startTranslateX: 0, // 初始水平位移为 0
  259. startTranslateY: 0, // 初始垂直位移为 0
  260. startCropBoxWidth: 0, // 初始裁剪框宽度为 0
  261. startCropBoxHeight: 0, // 初始裁剪框高度为 0
  262. isTouching: false, // 初始触摸状态为未触摸
  263. mode: "", // 初始触摸模式为空
  264. direction: "" // 初始调整方向为空
  265. });
  266. // 是否正在调整裁剪框大小
  267. const isResizing = ref(false);
  268. // 是否显示九宫格辅助线
  269. const showGuideLines = ref(false);
  270. // 图片翻转状态
  271. const flipHorizontal = ref(false); // 水平翻转状态
  272. const flipVertical = ref(false); // 垂直翻转状态
  273. // 图片旋转状态
  274. const rotate = ref(0); // 旋转状态
  275. // 计算图片样式
  276. const imageStyle = computed(() => {
  277. // 构建翻转变换
  278. const flipX = flipHorizontal.value ? "scaleX(-1)" : "scaleX(1)";
  279. const flipY = flipVertical.value ? "scaleY(-1)" : "scaleY(1)";
  280. // 创建基础样式对象
  281. const style = {
  282. transform: `translate(${toPixel(transform.translateX)}px, ${toPixel(transform.translateY)}px) ${flipX} ${flipY} rotate(${rotate.value}deg)`, // 设置图片位移和翻转变换
  283. height: toPixel(imageSize.height) + "px", // 设置图片显示高度
  284. width: toPixel(imageSize.width) + "px" // 设置图片显示宽度
  285. };
  286. // 如果不在触摸状态,添加过渡动画
  287. if (!touch.isTouching) {
  288. style["transitionDuration"] = "0.3s"; // 设置过渡动画时长
  289. }
  290. // 返回样式对象
  291. return style;
  292. });
  293. // 计算裁剪框样式
  294. const cropBoxStyle = computed(() => {
  295. // 返回裁剪框定位和尺寸样式
  296. return {
  297. left: `${toPixel(cropBox.x)}px`, // 设置裁剪框左边距
  298. top: `${toPixel(cropBox.y)}px`, // 设置裁剪框上边距
  299. width: `${toPixel(cropBox.width)}px`, // 设置裁剪框宽度
  300. height: `${toPixel(cropBox.height)}px` // 设置裁剪框高度
  301. };
  302. });
  303. // 计算遮罩层样式
  304. const maskStyle = computed<MaskStyle>(() => {
  305. // 返回四个方向的遮罩样式
  306. return {
  307. // 上方遮罩样式
  308. top: {
  309. height: `${toPixel(cropBox.y)}px`, // 遮罩高度到裁剪框顶部
  310. width: `${toPixel(cropBox.width)}px`, // 遮罩宽度占满容器
  311. left: `${toPixel(cropBox.x)}px`
  312. },
  313. // 右侧遮罩样式
  314. right: {
  315. width: `${toPixel(container.width - cropBox.x - cropBox.width)}px`, // 遮罩宽度为容器宽度减去裁剪框右边距
  316. height: "100%", // 遮罩高度与裁剪框相同
  317. top: 0, // 遮罩顶部对齐裁剪框
  318. left: `${toPixel(cropBox.x + cropBox.width)}px` // 遮罩贴右边
  319. },
  320. // 下方遮罩样式
  321. bottom: {
  322. height: `${toPixel(container.height - cropBox.y - cropBox.height)}px`, // 遮罩高度为容器高度减去裁剪框下边距
  323. width: `${toPixel(cropBox.width)}px`, // 遮罩宽度占满容器
  324. bottom: 0, // 遮罩贴底部
  325. left: `${toPixel(cropBox.x)}px`
  326. },
  327. // 左侧遮罩样式
  328. left: {
  329. width: `${toPixel(cropBox.x)}px`, // 遮罩宽度到裁剪框左边
  330. height: "100%", // 遮罩高度与裁剪框相同
  331. left: 0
  332. }
  333. };
  334. });
  335. // 底部按钮组样式
  336. const opStyle = computed(() => {
  337. let bottom = getSafeAreaHeight("bottom");
  338. if (bottom == 0) {
  339. bottom = 10;
  340. }
  341. return {
  342. bottom: bottom + "px"
  343. };
  344. });
  345. // 计算旋转后图片的有效尺寸的函数
  346. function getRotatedImageSize(): Size {
  347. // 获取旋转角度(转换为0-360度范围内的正值)
  348. const angle = ((rotate.value % 360) + 360) % 360;
  349. // 如果是90度或270度旋转,宽高需要交换
  350. if (angle == 90 || angle == 270) {
  351. return {
  352. width: imageSize.height,
  353. height: imageSize.width
  354. };
  355. }
  356. // 0度或180度旋转,宽高保持不变
  357. return {
  358. width: imageSize.width,
  359. height: imageSize.height
  360. };
  361. }
  362. // 计算双指缩放时的最小图片尺寸
  363. function getMinImageSizeForPinch(): Size {
  364. // 如果图片未加载,返回零尺寸
  365. if (!imageInfo.isLoaded) {
  366. return { width: 0, height: 0 };
  367. }
  368. // 计算图片原始宽高比
  369. const originalRatio = imageInfo.width / imageInfo.height;
  370. // 获取旋转角度
  371. const angle = ((rotate.value % 360) + 360) % 360;
  372. // 获取裁剪框需要的最小覆盖尺寸
  373. let requiredW: number; // 旋转后需要覆盖裁剪框宽度的图片实际尺寸
  374. let requiredH: number; // 旋转后需要覆盖裁剪框高度的图片实际尺寸
  375. if (angle == 90 || angle == 270) {
  376. // 旋转90度/270度时,图片的宽变成高,高变成宽
  377. // 所以图片实际宽度需要覆盖裁剪框高度,实际高度需要覆盖裁剪框宽度
  378. requiredW = cropBox.height;
  379. requiredH = cropBox.width;
  380. } else {
  381. // 0度或180度时,正常对应
  382. requiredW = cropBox.width;
  383. requiredH = cropBox.height;
  384. }
  385. // 根据图片原始比例,计算能满足覆盖要求的最小尺寸
  386. let minW: number;
  387. let minH: number;
  388. // 比较哪个约束更严格
  389. if (requiredW / originalRatio > requiredH) {
  390. // 宽度约束更严格
  391. minW = requiredW;
  392. minH = requiredW / originalRatio;
  393. } else {
  394. // 高度约束更严格
  395. minH = requiredH;
  396. minW = requiredH * originalRatio;
  397. }
  398. return {
  399. width: toPixel(minW),
  400. height: toPixel(minH)
  401. };
  402. }
  403. // 计算图片最小尺寸的函数
  404. function getMinImageSize(): Size {
  405. // 如果图片未加载或尺寸无效,返回零尺寸
  406. if (!imageInfo.isLoaded || imageInfo.width == 0 || imageInfo.height == 0) {
  407. return { width: 0, height: 0 }; // 返回空尺寸对象
  408. }
  409. // 获取考虑旋转后的图片有效宽高
  410. const angle = ((rotate.value % 360) + 360) % 360;
  411. let effectiveWidth = imageInfo.width;
  412. let effectiveHeight = imageInfo.height;
  413. // 如果旋转90度或270度,宽高交换
  414. if (angle == 90 || angle == 270) {
  415. effectiveWidth = imageInfo.height;
  416. effectiveHeight = imageInfo.width;
  417. }
  418. // 计算图片宽高比(使用旋转后的有效尺寸)
  419. const ratio = effectiveWidth / effectiveHeight;
  420. // 计算容器宽高比
  421. const containerRatio = container.width / container.height;
  422. // 声明基础显示尺寸变量
  423. let baseW: number; // 基础显示宽度
  424. let baseH: number; // 基础显示高度
  425. // 根据图片和容器的宽高比决定缩放方式
  426. if (ratio > containerRatio) {
  427. baseW = container.width; // 宽度占满容器
  428. baseH = container.width / ratio; // 高度按比例缩放
  429. } else {
  430. baseH = container.height; // 高度占满容器
  431. baseW = container.height * ratio; // 宽度按比例缩放
  432. }
  433. // 计算覆盖裁剪框所需的最小缩放比例
  434. const scaleW = cropBox.width / baseW; // 宽度缩放比例
  435. const scaleH = cropBox.height / baseH; // 高度缩放比例
  436. const minScale = Math.max(scaleW, scaleH); // 取最大缩放比例确保完全覆盖
  437. // 增加少量容差确保完全覆盖
  438. const finalScale = minScale * 1.01;
  439. // 返回最终尺寸
  440. return {
  441. width: toPixel(baseW * finalScale), // 计算最终宽度
  442. height: toPixel(baseH * finalScale) // 计算最终高度
  443. };
  444. }
  445. // 初始化裁剪框的函数
  446. function initCrop() {
  447. const { windowHeight, windowWidth } = uni.getWindowInfo();
  448. // 设置容器尺寸为视口尺寸
  449. container.height = windowHeight;
  450. container.width = windowWidth;
  451. // 设置裁剪框尺寸为传入的初始值
  452. cropBox.width = props.cropWidth; // 设置裁剪框宽度
  453. cropBox.height = props.cropHeight; // 设置裁剪框高度
  454. // 计算裁剪框居中位置
  455. cropBox.x = toPixel((container.width - cropBox.width) / 2); // 水平居中
  456. cropBox.y = toPixel((container.height - cropBox.height) / 2); // 垂直居中
  457. // 如果图片已加载,确保图片尺寸满足最小要求
  458. if (imageInfo.isLoaded) {
  459. const minSize = getMinImageSize(); // 获取最小尺寸
  460. // 如果当前尺寸小于最小尺寸,更新为最小尺寸
  461. if (imageSize.width < minSize.width || imageSize.height < minSize.height) {
  462. imageSize.width = toPixel(minSize.width); // 更新图片显示宽度
  463. imageSize.height = toPixel(minSize.height); // 更新图片显示高度
  464. }
  465. }
  466. }
  467. // 设置初始图片尺寸的函数
  468. function setInitialImageSize() {
  469. // 如果图片未加载或尺寸无效,直接返回
  470. if (!imageInfo.isLoaded || imageInfo.width == 0 || imageInfo.height == 0) {
  471. return; // 提前退出函数
  472. }
  473. // 计算图片宽高比
  474. const ratio = imageInfo.width / imageInfo.height;
  475. // 计算容器宽高比
  476. const containerRatio = container.width / container.height;
  477. // 声明基础显示尺寸变量
  478. let baseW: number; // 基础显示宽度
  479. let baseH: number; // 基础显示高度
  480. // 根据图片和容器的宽高比决定缩放方式
  481. if (ratio > containerRatio) {
  482. baseW = container.width; // 宽度占满容器
  483. baseH = container.width / ratio; // 高度按比例缩放
  484. } else {
  485. baseH = container.height; // 高度占满容器
  486. baseW = container.height * ratio; // 宽度按比例缩放
  487. }
  488. // 计算覆盖裁剪框所需的缩放比例
  489. const scaleW = cropBox.width / baseW; // 宽度缩放比例
  490. const scaleH = cropBox.height / baseH; // 高度缩放比例
  491. const scale = Math.max(scaleW, scaleH); // 取最大缩放比例
  492. // 设置图片显示尺寸
  493. imageSize.width = toPixel(baseW * scale); // 计算最终显示宽度
  494. imageSize.height = toPixel(baseH * scale); // 计算最终显示高度
  495. }
  496. // 调整图片边界的函数,确保图片完全覆盖裁剪框
  497. function adjustBounds() {
  498. // 如果图片未加载,直接返回
  499. if (!imageInfo.isLoaded) return;
  500. // 获取旋转后的图片有效尺寸
  501. const rotatedSize = getRotatedImageSize();
  502. // 计算图片中心点坐标
  503. const centerX = container.width / 2 + transform.translateX; // 图片中心 x 坐标
  504. const centerY = container.height / 2 + transform.translateY; // 图片中心 y 坐标
  505. // 计算旋转后图片四个边界坐标
  506. const imgLeft = centerX - rotatedSize.width / 2; // 图片左边界
  507. const imgRight = centerX + rotatedSize.width / 2; // 图片右边界
  508. const imgTop = centerY - rotatedSize.height / 2; // 图片上边界
  509. const imgBottom = centerY + rotatedSize.height / 2; // 图片下边界
  510. // 计算裁剪框四个边界坐标
  511. const cropLeft = cropBox.x; // 裁剪框左边界
  512. const cropRight = cropBox.x + cropBox.width; // 裁剪框右边界
  513. const cropTop = cropBox.y; // 裁剪框上边界
  514. const cropBottom = cropBox.y + cropBox.height; // 裁剪框下边界
  515. // 获取当前位移值
  516. let x = transform.translateX; // 当前水平位移
  517. let y = transform.translateY; // 当前垂直位移
  518. // 水平方向边界调整
  519. if (imgLeft > cropLeft) {
  520. x -= imgLeft - cropLeft; // 如果图片左边界超出裁剪框,向左调整
  521. } else if (imgRight < cropRight) {
  522. x += cropRight - imgRight; // 如果图片右边界不足,向右调整
  523. }
  524. // 垂直方向边界调整
  525. if (imgTop > cropTop) {
  526. y -= imgTop - cropTop; // 如果图片上边界超出裁剪框,向上调整
  527. } else if (imgBottom < cropBottom) {
  528. y += cropBottom - imgBottom; // 如果图片下边界不足,向下调整
  529. }
  530. // 应用调整后的位移值
  531. transform.translateX = toPixel(x); // 更新水平位移
  532. transform.translateY = toPixel(y); // 更新垂直位移
  533. }
  534. // 开始调整裁剪框尺寸的函数
  535. function onResizeStart(e: TouchEvent, direction: string) {
  536. // 设置调整状态
  537. touch.isTouching = true; // 标记正在触摸
  538. touch.mode = "resizing"; // 设置为调整尺寸模式
  539. touch.direction = direction; // 记录调整方向(tl/tr/bl/br)
  540. isResizing.value = true; // 标记正在调整尺寸
  541. showGuideLines.value = true; // 显示九宫格辅助线
  542. // 如果是单指触摸,记录初始状态
  543. if (e.touches.length == 1) {
  544. touch.startX = e.touches[0].clientX; // 记录起始 x 坐标
  545. touch.startY = e.touches[0].clientY; // 记录起始 y 坐标
  546. touch.startCropBoxWidth = cropBox.width; // 记录起始裁剪框宽度
  547. touch.startCropBoxHeight = cropBox.height; // 记录起始裁剪框高度
  548. }
  549. }
  550. // 处理调整裁剪框尺寸移动的函数
  551. function onResizeMove(e: TouchEvent) {
  552. // 如果组件不在触摸状态或不是调整模式,直接返回
  553. if (!touch.isTouching || touch.mode != "resizing") return;
  554. // 如果是单指触摸
  555. if (e.touches.length == 1) {
  556. // 计算位移差
  557. const dx = e.touches[0].clientX - touch.startX; // 水平位移差
  558. const dy = e.touches[0].clientY - touch.startY; // 垂直位移差
  559. const MIN_SIZE = 50; // 最小裁剪框尺寸
  560. // 保存当前裁剪框的固定锚点坐标
  561. let anchorX: number = 0; // 固定不动的锚点坐标
  562. let anchorY: number = 0; // 固定不动的锚点坐标
  563. let newX = cropBox.x; // 新的 x 坐标
  564. let newY = cropBox.y; // 新的 y 坐标
  565. let newW = cropBox.width; // 新的宽度
  566. let newH = cropBox.height; // 新的高度
  567. // 根据拖拽方向计算新尺寸,同时确定固定锚点
  568. switch (touch.direction) {
  569. case "tl": // 左上角拖拽,固定右下角
  570. anchorX = cropBox.x + cropBox.width; // 右边界固定
  571. anchorY = cropBox.y + cropBox.height; // 下边界固定
  572. newW = anchorX - (cropBox.x + dx); // 根据移动距离计算新宽度
  573. newH = anchorY - (cropBox.y + dy); // 根据移动距离计算新高度
  574. newX = anchorX - newW; // 根据新宽度计算新 x 坐标
  575. newY = anchorY - newH; // 根据新高度计算新 y 坐标
  576. break;
  577. case "tr": // 右上角拖拽,固定左下角
  578. anchorX = cropBox.x; // 左边界固定
  579. anchorY = cropBox.y + cropBox.height; // 下边界固定
  580. newW = cropBox.width + dx; // 宽度增加
  581. newH = anchorY - (cropBox.y + dy); // 根据移动距离计算新高度
  582. newX = anchorX; // x 坐标不变
  583. newY = anchorY - newH; // 根据新高度计算新 y 坐标
  584. break;
  585. case "bl": // 左下角拖拽,固定右上角
  586. anchorX = cropBox.x + cropBox.width; // 右边界固定
  587. anchorY = cropBox.y; // 上边界固定
  588. newW = anchorX - (cropBox.x + dx); // 根据移动距离计算新宽度
  589. newH = cropBox.height + dy; // 高度增加
  590. newX = anchorX - newW; // 根据新宽度计算新 x 坐标
  591. newY = anchorY; // y 坐标不变
  592. break;
  593. case "br": // 右下角拖拽,固定左上角
  594. anchorX = cropBox.x; // 左边界固定
  595. anchorY = cropBox.y; // 上边界固定
  596. newW = cropBox.width + dx; // 宽度增加
  597. newH = cropBox.height + dy; // 高度增加
  598. newX = anchorX; // x 坐标不变
  599. newY = anchorY; // y 坐标不变
  600. break;
  601. }
  602. // 确保尺寸不小于最小值,并相应调整坐标
  603. if (newW < MIN_SIZE) {
  604. newW = MIN_SIZE;
  605. // 根据拖拽方向调整坐标
  606. if (touch.direction == "tl" || touch.direction == "bl") {
  607. newX = anchorX - newW; // 左侧拖拽时调整 x 坐标
  608. }
  609. }
  610. if (newH < MIN_SIZE) {
  611. newH = MIN_SIZE;
  612. // 根据拖拽方向调整坐标
  613. if (touch.direction == "tl" || touch.direction == "tr") {
  614. newY = anchorY - newH; // 上侧拖拽时调整 y 坐标
  615. }
  616. }
  617. // 确保裁剪框在容器边界内
  618. newX = toPixel(Math.max(0, Math.min(newX, container.width - newW)));
  619. newY = toPixel(Math.max(0, Math.min(newY, container.height - newH)));
  620. // 当位置受限时,调整尺寸以保持锚点位置
  621. if (newX == 0 && (touch.direction == "tl" || touch.direction == "bl")) {
  622. newW = anchorX; // 左边界贴边时,调整宽度
  623. }
  624. if (newY == 0 && (touch.direction == "tl" || touch.direction == "tr")) {
  625. newH = anchorY; // 上边界贴边时,调整高度
  626. }
  627. if (
  628. newX + newW >= container.width &&
  629. (touch.direction == "tr" || touch.direction == "br")
  630. ) {
  631. newW = container.width - newX; // 右边界贴边时,调整宽度
  632. }
  633. if (
  634. newY + newH >= container.height &&
  635. (touch.direction == "bl" || touch.direction == "br")
  636. ) {
  637. newH = container.height - newY; // 下边界贴边时,调整高度
  638. }
  639. // 应用计算结果
  640. cropBox.x = toPixel(newX);
  641. cropBox.y = toPixel(newY);
  642. cropBox.width = toPixel(newW);
  643. cropBox.height = toPixel(newH);
  644. // 无论是否达到边界,都更新起始坐标,确保下次计算的连续性
  645. touch.startX = e.touches[0].clientX; // 更新起始 x 坐标
  646. touch.startY = e.touches[0].clientY; // 更新起始 y 坐标
  647. }
  648. }
  649. // 居中并调整图片和裁剪框的函数
  650. function centerAndAdjust() {
  651. // 如果图片未加载,直接返回
  652. if (!imageInfo.isLoaded) return;
  653. // 获取当前图片尺寸
  654. const currentW = imageSize.width; // 当前图片宽度
  655. const currentH = imageSize.height; // 当前图片高度
  656. // 计算裁剪框缩放比例
  657. const scaleX = cropBox.width / touch.startCropBoxWidth; // 水平缩放比例
  658. const scaleY = cropBox.height / touch.startCropBoxHeight; // 垂直缩放比例
  659. const cropScale = Math.max(scaleX, scaleY); // 取最大缩放比例
  660. // 计算图片反向缩放比例
  661. let imgScale = 1 / cropScale; // 图片缩放倍数(与裁剪框缩放相反)
  662. // 计算调整后的图片尺寸
  663. let newW = currentW * imgScale; // 新的图片宽度
  664. let newH = currentH * imgScale; // 新的图片高度
  665. // 获取旋转后的图片有效尺寸,用于正确计算覆盖裁剪框的最小尺寸
  666. const getRotatedSize = (w: number, h: number): Size => {
  667. const angle = ((rotate.value % 360) + 360) % 360;
  668. if (angle == 90 || angle == 270) {
  669. return { width: h, height: w }; // 旋转90度/270度时宽高交换
  670. }
  671. return { width: w, height: h };
  672. };
  673. // 获取调整后图片的旋转有效尺寸
  674. const rotatedSize = getRotatedSize(newW, newH);
  675. // 确保图片能完全覆盖裁剪框(使用旋转后的有效尺寸)
  676. const minScaleW = cropBox.width / rotatedSize.width; // 宽度最小缩放比例
  677. const minScaleH = cropBox.height / rotatedSize.height; // 高度最小缩放比例
  678. const minScale = Math.max(minScaleW, minScaleH); // 取最大值确保完全覆盖
  679. // 如果需要进一步放大图片
  680. if (minScale > 1) {
  681. imgScale *= minScale; // 调整缩放倍数
  682. newW = currentW * imgScale; // 重新计算宽度
  683. newH = currentH * imgScale; // 重新计算高度
  684. }
  685. // 应用 maxScale 限制,保持图片比例
  686. const maxW = container.width * props.maxScale; // 最大宽度限制
  687. const maxH = container.height * props.maxScale; // 最大高度限制
  688. // 计算统一的最大缩放约束
  689. const maxScaleW = maxW / newW; // 最大宽度缩放比例
  690. const maxScaleH = maxH / newH; // 最大高度缩放比例
  691. const maxScaleConstraint = Math.min(maxScaleW, maxScaleH, 1); // 最大缩放约束
  692. // 应用最大缩放约束,保持比例
  693. newW = newW * maxScaleConstraint; // 应用最大缩放限制
  694. newH = newH * maxScaleConstraint; // 应用最大缩放限制
  695. // 应用新的图片尺寸
  696. imageSize.width = toPixel(newW); // 更新图片显示宽度
  697. imageSize.height = toPixel(newH); // 更新图片显示高度
  698. // 将裁剪框居中显示
  699. cropBox.x = toPixel((container.width - cropBox.width) / 2); // 水平居中
  700. cropBox.y = toPixel((container.height - cropBox.height) / 2); // 垂直居中
  701. // 重置图片位移到居中位置
  702. transform.translateX = 0; // 重置水平位移
  703. transform.translateY = 0; // 重置垂直位移
  704. // 调整图片边界
  705. adjustBounds(); // 确保图片完全覆盖裁剪框
  706. }
  707. // 处理调整尺寸结束事件的函数
  708. function onResizeEnd() {
  709. // 重置触摸状态
  710. touch.isTouching = false; // 标记触摸结束
  711. touch.mode = ""; // 清空触摸模式
  712. touch.direction = ""; // 清空调整方向
  713. isResizing.value = false; // 标记停止调整尺寸
  714. // 执行居中和调整
  715. centerAndAdjust(); // 重新调整图片和裁剪框
  716. // 延迟隐藏辅助线
  717. setTimeout(() => {
  718. showGuideLines.value = false; // 隐藏九宫格辅助线
  719. }, 200); // 200ms 后隐藏
  720. }
  721. // 处理图片触摸开始事件的函数
  722. function onTouchStart(e: TouchEvent) {
  723. // 如果组件图片未加载,直接返回
  724. if (!imageInfo.isLoaded) return;
  725. // 设置触摸状态
  726. touch.isTouching = true; // 标记正在触摸
  727. touch.mode = "image"; // 设置触摸模式为图片操作
  728. // 根据触摸点数量判断操作类型
  729. if (e.touches.length == 1) {
  730. // 单指拖拽模式
  731. touch.startX = e.touches[0].clientX; // 记录起始 x 坐标
  732. touch.startY = e.touches[0].clientY; // 记录起始 y 坐标
  733. touch.startTranslateX = transform.translateX; // 记录起始水平位移
  734. touch.startTranslateY = transform.translateY; // 记录起始垂直位移
  735. } else if (e.touches.length == 2) {
  736. // 双指缩放模式
  737. const t1 = e.touches[0]; // 第一个触摸点
  738. const t2 = e.touches[1]; // 第二个触摸点
  739. // 计算两个触摸点之间的初始距离
  740. touch.startDistance = Math.sqrt(
  741. Math.pow(t2.clientX - t1.clientX, 2) + Math.pow(t2.clientY - t1.clientY, 2)
  742. );
  743. // 记录触摸开始时的图片尺寸
  744. touch.startImageWidth = imageSize.width; // 起始图片宽度
  745. touch.startImageHeight = imageSize.height; // 起始图片高度
  746. // 计算并记录缩放中心点(两个触摸点的中点)
  747. touch.startX = (t1.clientX + t2.clientX) / 2; // 缩放中心 x 坐标
  748. touch.startY = (t1.clientY + t2.clientY) / 2; // 缩放中心 y 坐标
  749. // 记录触摸开始时的位移状态
  750. touch.startTranslateX = transform.translateX; // 起始水平位移
  751. touch.startTranslateY = transform.translateY; // 起始垂直位移
  752. }
  753. }
  754. // 处理图片触摸移动事件的函数
  755. function onTouchMove(e: TouchEvent) {
  756. if (!touch.isTouching) return;
  757. if (touch.mode == "resizing") {
  758. onResizeMove(e);
  759. return;
  760. }
  761. // 根据触摸点数量判断操作类型
  762. if (e.touches.length == 1) {
  763. // 单指拖拽模式
  764. const dx = e.touches[0].clientX - touch.startX; // 计算水平位移差
  765. const dy = e.touches[0].clientY - touch.startY; // 计算垂直位移差
  766. // 更新图片位移
  767. transform.translateX = toPixel(touch.startTranslateX + dx); // 应用水平位移
  768. transform.translateY = toPixel(touch.startTranslateY + dy); // 应用垂直位移
  769. } else if (e.touches.length == 2) {
  770. // 双指缩放模式
  771. const t1 = e.touches[0]; // 第一个触摸点
  772. const t2 = e.touches[1]; // 第二个触摸点
  773. // 计算当前两个触摸点之间的距离
  774. const distance = Math.sqrt(
  775. Math.pow(t2.clientX - t1.clientX, 2) + Math.pow(t2.clientY - t1.clientY, 2)
  776. );
  777. // 计算缩放倍数(当前距离 / 初始距离)
  778. const scale = distance / touch.startDistance;
  779. // 计算缩放后的新尺寸
  780. const newW = touch.startImageWidth * scale; // 新宽度
  781. const newH = touch.startImageHeight * scale; // 新高度
  782. // 获取尺寸约束条件
  783. const minSize = getMinImageSizeForPinch(); // 最小尺寸限制(专门用于双指缩放)
  784. const maxW = container.width * props.maxScale; // 最大宽度限制
  785. const maxH = container.height * props.maxScale; // 最大高度限制
  786. // 计算统一的缩放约束,保持图片比例
  787. const minScaleW = minSize.width / newW; // 最小宽度缩放比例
  788. const minScaleH = minSize.height / newH; // 最小高度缩放比例
  789. const maxScaleW = maxW / newW; // 最大宽度缩放比例
  790. const maxScaleH = maxH / newH; // 最大高度缩放比例
  791. // 取最严格的约束条件,确保图片不变形
  792. const minScale = Math.max(minScaleW, minScaleH); // 最小缩放约束
  793. const maxScale = Math.min(maxScaleW, maxScaleH); // 最大缩放约束
  794. const finalScale = Math.max(minScale, Math.min(maxScale, 1)); // 最终统一缩放比例
  795. // 应用统一的缩放比例,保持图片原始比例
  796. const finalW = newW * finalScale; // 最终宽度
  797. const finalH = newH * finalScale; // 最终高度
  798. // 计算当前缩放中心点
  799. const centerX = (t1.clientX + t2.clientX) / 2; // 缩放中心 x 坐标
  800. const centerY = (t1.clientY + t2.clientY) / 2; // 缩放中心 y 坐标
  801. // 计算尺寸变化量
  802. const dw = finalW - touch.startImageWidth; // 宽度变化量
  803. const dh = finalH - touch.startImageHeight; // 高度变化量
  804. // 计算位移补偿,使缩放围绕触摸中心进行
  805. const offsetX = ((centerX - container.width / 2) * dw) / (2 * touch.startImageWidth); // 水平位移补偿
  806. const offsetY = ((centerY - container.height / 2) * dh) / (2 * touch.startImageHeight); // 垂直位移补偿
  807. // 更新图片尺寸和位移
  808. imageSize.width = toPixel(finalW); // 应用新宽度
  809. imageSize.height = toPixel(finalH); // 应用新高度
  810. transform.translateX = toPixel(touch.startTranslateX - offsetX); // 应用补偿后的水平位移
  811. transform.translateY = toPixel(touch.startTranslateY - offsetY); // 应用补偿后的垂直位移
  812. }
  813. }
  814. // 处理图片触摸结束事件的函数
  815. function onTouchEnd() {
  816. if (touch.mode == "resizing") {
  817. onResizeEnd();
  818. return;
  819. }
  820. // 重置触摸状态
  821. touch.isTouching = false; // 标记触摸结束
  822. touch.mode = ""; // 清空触摸模式
  823. // 调整图片边界确保完全覆盖裁剪框
  824. adjustBounds(); // 执行边界调整
  825. }
  826. // 重置裁剪器到初始状态的函数
  827. function reset() {
  828. // 重新初始化裁剪框
  829. initCrop(); // 恢复裁剪框到初始位置和尺寸
  830. // 重置翻转状态
  831. flipHorizontal.value = false; // 重置水平翻转状态
  832. flipVertical.value = false; // 重置垂直翻转状态
  833. rotate.value = 0; // 重置旋转角度
  834. // 重置图片位移
  835. transform.translateX = 0;
  836. transform.translateY = 0;
  837. // 根据图片加载状态进行不同处理
  838. if (imageInfo.isLoaded) {
  839. setInitialImageSize(); // 重新设置图片初始尺寸
  840. adjustBounds(); // 调整图片边界
  841. } else {
  842. // 如果图片未加载,重置所有状态
  843. imageSize.width = toPixel(0); // 重置图片显示宽度
  844. imageSize.height = toPixel(0); // 重置图片显示高度
  845. transform.translateX = toPixel(0); // 重置水平位移
  846. transform.translateY = toPixel(0); // 重置垂直位移
  847. }
  848. }
  849. // 是否显示
  850. const visible = ref(false);
  851. // 图片地址
  852. const imageUrl = ref("");
  853. // 打开裁剪器
  854. function open(url: string) {
  855. visible.value = true;
  856. nextTick(() => {
  857. imageUrl.value = url;
  858. });
  859. }
  860. // 关闭裁剪器
  861. function close() {
  862. visible.value = false;
  863. }
  864. // 重新选择图片
  865. function chooseImage() {
  866. uni.chooseImage({
  867. count: 1,
  868. sizeType: ["original", "compressed"],
  869. sourceType: ["album", "camera"],
  870. success: (res) => {
  871. if (res.tempFilePaths.length > 0) {
  872. open(res.tempFilePaths[0]);
  873. }
  874. }
  875. });
  876. }
  877. // 处理图片加载完成事件的函数
  878. function onImageLoaded(e: UniImageLoadEvent) {
  879. // 更新图片原始尺寸信息
  880. imageInfo.width = e.detail.width; // 保存图片原始宽度
  881. imageInfo.height = e.detail.height; // 保存图片原始高度
  882. imageInfo.isLoaded = true; // 标记图片已加载
  883. reset(); // 重置裁剪框
  884. // 触发加载完成事件
  885. emit("load", e); // 向父组件发送加载事件
  886. }
  887. // 切换水平翻转状态的函数
  888. function toggleHorizontalFlip() {
  889. flipHorizontal.value = !flipHorizontal.value; // 切换水平翻转状态
  890. }
  891. // 切换垂直翻转状态的函数
  892. function toggleVerticalFlip() {
  893. flipVertical.value = !flipVertical.value; // 切换垂直翻转状态
  894. }
  895. // 90度旋转
  896. function rotate90() {
  897. rotate.value -= 90; // 旋转90度(逆时针)
  898. // 如果图片已加载,检查旋转后是否还能覆盖裁剪框
  899. if (imageInfo.isLoaded) {
  900. // 获取旋转后的有效尺寸
  901. const rotatedSize = getRotatedImageSize();
  902. // 检查旋转后的有效尺寸是否能完全覆盖裁剪框
  903. const scaleW = cropBox.width / rotatedSize.width; // 宽度需要的缩放比例
  904. const scaleH = cropBox.height / rotatedSize.height; // 高度需要的缩放比例
  905. const requiredScale = Math.max(scaleW, scaleH); // 取最大比例确保完全覆盖
  906. // 如果需要放大图片(旋转后尺寸不够覆盖裁剪框)
  907. if (requiredScale > 1) {
  908. // 同比例放大图片尺寸
  909. imageSize.width = toPixel(imageSize.width * requiredScale);
  910. imageSize.height = toPixel(imageSize.height * requiredScale);
  911. }
  912. // 调整边界确保图片完全覆盖裁剪框
  913. adjustBounds();
  914. }
  915. }
  916. // 执行裁剪转图片
  917. async function toPng(): Promise<string> {
  918. return new Promise((resolve) => {
  919. uni.createCanvasContextAsync({
  920. id: canvasId,
  921. component: proxy,
  922. success: (context: CanvasContext) => {
  923. // 获取设备像素比
  924. const dpr = getDevicePixelRatio();
  925. // 获取绘图上下文
  926. const ctx = context.getContext("2d")!;
  927. // 设置宽高
  928. ctx!.canvas.width = cropBox.width * dpr;
  929. ctx!.canvas.height = cropBox.height * dpr;
  930. // #ifdef APP
  931. ctx!.reset();
  932. // #endif
  933. // #ifndef APP
  934. ctx!.clearRect(0, 0, cropBox.width * dpr, cropBox.height * dpr);
  935. // #endif
  936. // 创建图片
  937. let img: Image;
  938. // 微信小程序环境创建图片
  939. // #ifdef MP-WEIXIN || APP-HARMONY
  940. img = context.createImage();
  941. // #endif
  942. // 其他环境创建图片
  943. // #ifndef MP-WEIXIN || APP-HARMONY
  944. img = new Image();
  945. // #endif
  946. // 设置图片源并在加载完成后绘制
  947. img.src = imageUrl.value;
  948. img.onload = () => {
  949. let x: number;
  950. let y: number;
  951. // 根据旋转角度计算裁剪位置
  952. switch (Math.abs(rotate.value) % 360) {
  953. case 270:
  954. // 旋转270度时的位置计算
  955. x = (imageSize.width - cropBox.height) / 2 - transform.translateY;
  956. y = (imageSize.height + cropBox.width) / 2 + transform.translateX;
  957. break;
  958. case 180:
  959. // 旋转180度时的位置计算
  960. x = (imageSize.width + cropBox.width) / 2 + transform.translateX;
  961. y = (imageSize.height + cropBox.height) / 2 + transform.translateY;
  962. break;
  963. case 90:
  964. // 旋转90度时的位置计算
  965. x = (imageSize.width + cropBox.height) / 2 + transform.translateY;
  966. y = (imageSize.height - cropBox.width) / 2 - transform.translateX;
  967. break;
  968. default:
  969. // 不旋转时的位置计算
  970. x = (imageSize.width - cropBox.width) / 2 - transform.translateX;
  971. y = (imageSize.height - cropBox.height) / 2 - transform.translateY;
  972. break;
  973. }
  974. if (x < 0) {
  975. x = 0;
  976. }
  977. if (y < 0) {
  978. y = 0;
  979. }
  980. // 图片旋转
  981. ctx!.rotate((rotate.value * Math.PI) / 180);
  982. // 绘制图片
  983. ctx!.drawImage(
  984. img,
  985. -x * dpr,
  986. -y * dpr,
  987. imageSize.width * dpr,
  988. imageSize.height * dpr
  989. );
  990. setTimeout(() => {
  991. canvasToPng(canvasRef.value!).then((url) => {
  992. emit("crop", url);
  993. resolve(url);
  994. });
  995. }, 10);
  996. };
  997. }
  998. });
  999. });
  1000. }
  1001. defineExpose({
  1002. open,
  1003. close,
  1004. chooseImage,
  1005. toPng
  1006. });
  1007. </script>
  1008. <style lang="scss" scoped>
  1009. .cl-cropper {
  1010. @apply bg-black absolute left-0 top-0 w-full h-full;
  1011. z-index: 510;
  1012. &__image {
  1013. @apply absolute top-0 left-0 flex items-center justify-center w-full h-full pointer-events-none;
  1014. }
  1015. &__mask {
  1016. @apply absolute top-0 left-0 w-full h-full z-10 pointer-events-none;
  1017. &-item {
  1018. @apply absolute;
  1019. background-color: rgba(0, 0, 0, 0.4);
  1020. }
  1021. }
  1022. &__crop-box {
  1023. @apply absolute overflow-visible;
  1024. z-index: 10;
  1025. }
  1026. &__crop-area {
  1027. @apply relative w-full h-full overflow-visible duration-200 pointer-events-none;
  1028. @apply border border-solid;
  1029. border-color: rgba(255, 255, 255, 0.5);
  1030. &.is-resizing {
  1031. @apply border-primary-500;
  1032. }
  1033. }
  1034. &__guide-lines {
  1035. @apply flex justify-center items-center;
  1036. @apply absolute top-0 left-0 w-full h-full pointer-events-none opacity-0 duration-200;
  1037. &.is-show {
  1038. @apply opacity-100;
  1039. }
  1040. }
  1041. &__guide-line {
  1042. @apply absolute bg-white opacity-70;
  1043. &--h1 {
  1044. @apply top-1/3 left-0 w-full;
  1045. height: 1px;
  1046. }
  1047. &--h2 {
  1048. @apply top-2/3 left-0 w-full;
  1049. height: 1px;
  1050. }
  1051. &--v1 {
  1052. @apply left-1/3 top-0 h-full;
  1053. width: 1px;
  1054. }
  1055. &--v2 {
  1056. @apply left-2/3 top-0 h-full;
  1057. width: 1px;
  1058. }
  1059. }
  1060. &__guide-text {
  1061. @apply absolute flex flex-row items-center justify-center;
  1062. }
  1063. &__corner-indicator {
  1064. @apply border-white border-solid border-b-transparent border-l-transparent absolute duration-200;
  1065. width: 20px;
  1066. height: 20px;
  1067. border-width: 1px;
  1068. }
  1069. &__drag-point {
  1070. @apply absolute duration-200 flex items-center justify-center overflow-visible;
  1071. width: 40px;
  1072. height: 40px;
  1073. &--tl {
  1074. top: 0;
  1075. left: 0;
  1076. .cl-cropper__corner-indicator {
  1077. transform: rotate(-90deg);
  1078. left: -1px;
  1079. top: -1px;
  1080. }
  1081. }
  1082. &--tr {
  1083. top: 0;
  1084. right: 0;
  1085. .cl-cropper__corner-indicator {
  1086. transform: rotate(0deg);
  1087. right: -1px;
  1088. top: -1px;
  1089. }
  1090. }
  1091. &--bl {
  1092. bottom: 0;
  1093. left: 0;
  1094. .cl-cropper__corner-indicator {
  1095. transform: rotate(180deg);
  1096. bottom: -1px;
  1097. left: -1px;
  1098. }
  1099. }
  1100. &--br {
  1101. bottom: 0;
  1102. right: 0;
  1103. .cl-cropper__corner-indicator {
  1104. transform: rotate(90deg);
  1105. bottom: -1px;
  1106. right: 0-1px;
  1107. }
  1108. }
  1109. }
  1110. &__op {
  1111. @apply absolute left-0 bottom-0 w-full flex flex-row justify-between;
  1112. z-index: 30;
  1113. height: 40px;
  1114. &-item {
  1115. @apply flex flex-row justify-center items-center flex-1 h-full;
  1116. }
  1117. }
  1118. &__canvas {
  1119. @apply absolute top-0;
  1120. left: -10000px;
  1121. }
  1122. }
  1123. </style>