cl-cropper.uvue 40 KB

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