cl-sign.uvue 7.1 KB

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