cl-sign.uvue 7.1 KB

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