cl-sign.uvue 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. <template>
  2. <view class="cl-sign" :class="[pt.className]">
  3. <canvas
  4. class="cl-sign__canvas"
  5. :id="canvasId"
  6. :style="{
  7. height: `${size.height}px`,
  8. width: `${size.width}px`
  9. }"
  10. @touchstart="onTouchStart"
  11. @touchmove="onTouchMove"
  12. @touchend="onTouchEnd"
  13. ></canvas>
  14. </view>
  15. </template>
  16. <script lang="ts" setup>
  17. import { parsePt, uuid } from "@/cool";
  18. import { computed, getCurrentInstance, onMounted, onUnmounted, ref, watch } from "vue";
  19. defineOptions({
  20. name: "cl-sign"
  21. });
  22. const props = defineProps({
  23. pt: {
  24. type: Object,
  25. default: () => ({})
  26. },
  27. // 画布宽度
  28. width: {
  29. type: Number,
  30. default: 300
  31. },
  32. // 画布高度
  33. height: {
  34. type: Number,
  35. default: 200
  36. },
  37. // 线条颜色
  38. strokeColor: {
  39. type: String,
  40. default: "#000000"
  41. },
  42. // 线条宽度
  43. strokeWidth: {
  44. type: Number,
  45. default: 3
  46. },
  47. // 背景颜色
  48. backgroundColor: {
  49. type: String,
  50. default: "#ffffff"
  51. },
  52. // 是否启用毛笔效果
  53. enableBrush: {
  54. type: Boolean,
  55. default: true
  56. },
  57. // 最小线条宽度
  58. minStrokeWidth: {
  59. type: Number,
  60. default: 1
  61. },
  62. // 最大线条宽度
  63. maxStrokeWidth: {
  64. type: Number,
  65. default: 6
  66. },
  67. // 速度敏感度
  68. velocitySensitivity: {
  69. type: Number,
  70. default: 0.7
  71. },
  72. // 是否支持横屏自适应
  73. autoRotate: {
  74. type: Boolean,
  75. default: true
  76. },
  77. // 是否全屏
  78. fullscreen: {
  79. type: Boolean,
  80. default: false
  81. }
  82. });
  83. const emit = defineEmits(["change"]);
  84. const { proxy } = getCurrentInstance()!;
  85. const { windowWidth, windowHeight } = uni.getWindowInfo();
  86. // 触摸点类型
  87. type Point = { x: number; y: number; time: number };
  88. // 透传样式类型定义
  89. type PassThrough = {
  90. className?: string;
  91. };
  92. // 解析透传样式配置
  93. const pt = computed(() => parsePt<PassThrough>(props.pt));
  94. // canvas组件上下文
  95. let canvasCtx: CanvasContext | null = null;
  96. // 绘图上下文
  97. let drawCtx: CanvasRenderingContext2D | null = null;
  98. // 生成唯一的canvas ID
  99. const canvasId = `cl-sign__${uuid()}`;
  100. // 触摸状态
  101. const isDrawing = ref(false);
  102. // 上一个触摸点
  103. let lastPoint: Point | null = null;
  104. // 当前线条宽度
  105. let currentStrokeWidth = ref(3);
  106. // 速度缓冲数组(用于平滑速度变化)
  107. const velocityBuffer: number[] = [];
  108. // 当前是否为横屏
  109. const isLandscape = ref(false);
  110. // 动态计算的画布尺寸
  111. const size = computed(() => {
  112. if (props.fullscreen) {
  113. const { windowWidth, windowHeight } = uni.getWindowInfo();
  114. return {
  115. width: windowWidth,
  116. height: windowHeight
  117. };
  118. }
  119. if (isLandscape.value) {
  120. const { windowWidth } = uni.getWindowInfo();
  121. return {
  122. width: windowWidth,
  123. height: props.height
  124. };
  125. }
  126. return {
  127. width: props.width,
  128. height: props.height
  129. };
  130. });
  131. // 获取触摸点在canvas中的坐标
  132. function getTouchPos(e: TouchEvent): Point {
  133. const touch = e.touches[0];
  134. const rect = (e.target as any).getBoundingClientRect();
  135. return {
  136. x: touch.clientX - rect.left,
  137. y: touch.clientY - rect.top,
  138. time: Date.now()
  139. };
  140. }
  141. // 计算速度并返回动态线条宽度
  142. function calculateStrokeWidth(currentPoint: Point): number {
  143. if (!lastPoint || !props.enableBrush) {
  144. return props.strokeWidth;
  145. }
  146. // 计算距离和时间差
  147. const distance = Math.sqrt(
  148. Math.pow(currentPoint.x - lastPoint.x, 2) + Math.pow(currentPoint.y - lastPoint.y, 2)
  149. );
  150. const timeDelta = currentPoint.time - lastPoint.time;
  151. if (timeDelta <= 0) return currentStrokeWidth.value;
  152. // 计算速度 (像素/毫秒)
  153. const velocity = distance / timeDelta;
  154. // 添加到速度缓冲区(用于平滑)
  155. velocityBuffer.push(velocity);
  156. if (velocityBuffer.length > 5) {
  157. velocityBuffer.shift();
  158. }
  159. // 计算平均速度
  160. const avgVelocity = velocityBuffer.reduce((sum, v) => sum + v, 0) / velocityBuffer.length;
  161. // 根据速度计算线条宽度(速度越快越细)
  162. const normalizedVelocity = Math.min(avgVelocity * props.velocitySensitivity, 1);
  163. const widthRange = props.maxStrokeWidth - props.minStrokeWidth;
  164. const targetWidth = props.maxStrokeWidth - normalizedVelocity * widthRange;
  165. // 平滑过渡到目标宽度
  166. const smoothFactor = 0.3;
  167. return currentStrokeWidth.value + (targetWidth - currentStrokeWidth.value) * smoothFactor;
  168. }
  169. // 触摸开始
  170. function onTouchStart(e: TouchEvent) {
  171. e.preventDefault();
  172. isDrawing.value = true;
  173. lastPoint = getTouchPos(e);
  174. // 初始化线条宽度和清空速度缓冲
  175. currentStrokeWidth.value = props.enableBrush ? props.maxStrokeWidth : props.strokeWidth;
  176. velocityBuffer.length = 0;
  177. }
  178. // 触摸移动
  179. function onTouchMove(e: TouchEvent) {
  180. e.preventDefault();
  181. if (!isDrawing.value || !lastPoint || !drawCtx) return;
  182. const currentPoint = getTouchPos(e);
  183. // 计算动态线条宽度
  184. const strokeWidth = calculateStrokeWidth(currentPoint);
  185. currentStrokeWidth.value = strokeWidth;
  186. // 绘制线条
  187. drawCtx!.beginPath();
  188. drawCtx!.moveTo(lastPoint.x, lastPoint.y);
  189. drawCtx!.lineTo(currentPoint.x, currentPoint.y);
  190. drawCtx!.strokeStyle = props.strokeColor;
  191. drawCtx!.lineWidth = strokeWidth;
  192. drawCtx!.lineCap = "round";
  193. drawCtx!.lineJoin = "round";
  194. drawCtx!.stroke();
  195. lastPoint = currentPoint;
  196. emit("change");
  197. }
  198. // 触摸结束
  199. function onTouchEnd(e: TouchEvent) {
  200. e.preventDefault();
  201. isDrawing.value = false;
  202. lastPoint = null;
  203. }
  204. // 判断横竖屏
  205. function getOrientation() {
  206. const { windowHeight, windowWidth } = uni.getWindowInfo();
  207. // 判断是否为横屏(宽度大于高度)
  208. isLandscape.value = windowWidth > windowHeight;
  209. }
  210. // 屏幕方向变化监听
  211. function onOrientationChange() {
  212. setTimeout(() => {
  213. getOrientation();
  214. // 重新初始化画布
  215. if (props.autoRotate) {
  216. initCanvas();
  217. }
  218. }, 300); // 延迟确保屏幕方向变化完成
  219. }
  220. // 清除画布
  221. function clear() {
  222. if (!drawCtx) return;
  223. const { width, height } = size.value;
  224. // #ifdef APP
  225. drawCtx!.reset();
  226. // #endif
  227. // #ifndef APP
  228. drawCtx!.clearRect(0, 0, width, height);
  229. // #endif
  230. // 填充背景色
  231. drawCtx!.fillStyle = props.backgroundColor;
  232. drawCtx!.fillRect(0, 0, width, height);
  233. emit("change");
  234. }
  235. // 获取签名图片
  236. function toPng(): Promise<string> {
  237. return new Promise((resolve, reject) => {
  238. if (!canvasCtx) {
  239. reject(new Error("Canvas context not initialized"));
  240. return;
  241. }
  242. uni.canvasToTempFilePath(
  243. {
  244. canvasId: canvasId,
  245. success: (res) => {
  246. resolve(res.tempFilePath);
  247. },
  248. fail: (err) => {
  249. reject(err);
  250. }
  251. },
  252. proxy
  253. );
  254. });
  255. }
  256. // 初始化画布
  257. function initCanvas() {
  258. const { width, height } = size.value;
  259. uni.createCanvasContextAsync({
  260. id: canvasId,
  261. component: proxy,
  262. success: (context: CanvasContext) => {
  263. // 设置canvas上下文
  264. canvasCtx = context;
  265. // 获取绘图上下文
  266. drawCtx = context.getContext("2d")!;
  267. // 设置宽高
  268. drawCtx!.canvas.width = width;
  269. drawCtx!.canvas.height = height;
  270. // 优化渲染质量
  271. drawCtx!.textBaseline = "middle";
  272. drawCtx!.textAlign = "center";
  273. drawCtx!.miterLimit = 10;
  274. // 初始化背景
  275. clear();
  276. }
  277. });
  278. }
  279. onMounted(() => {
  280. // 判断横屏竖屏
  281. getOrientation();
  282. // 初始化画布
  283. initCanvas();
  284. // 监听屏幕方向变化
  285. if (props.autoRotate) {
  286. uni.onWindowResize(onOrientationChange);
  287. }
  288. // 监听全屏状态变化
  289. watch(
  290. () => props.fullscreen,
  291. () => {
  292. initCanvas();
  293. }
  294. );
  295. });
  296. onUnmounted(() => {
  297. // 移除屏幕方向监听
  298. if (props.autoRotate) {
  299. uni.offWindowResize(onOrientationChange);
  300. }
  301. });
  302. defineExpose({
  303. clear,
  304. toPng
  305. });
  306. </script>