cl-sign.uvue 7.0 KB

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