cl-sign.uvue 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. autoRotate: {
  75. type: Boolean,
  76. default: true
  77. }
  78. });
  79. const emit = defineEmits(["change"]);
  80. const { proxy } = getCurrentInstance()!;
  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, lastPoint!.y);
  207. drawCtx!.lineTo(currentPoint.x, currentPoint.y);
  208. drawCtx!.strokeStyle = props.strokeColor;
  209. drawCtx!.lineWidth = strokeWidth;
  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, props.height);
  230. // #endif
  231. // 获取设备像素比
  232. const dpr = uni.getDeviceInfo().devicePixelRatio ?? 1;
  233. // #ifndef H5
  234. // 设置缩放比例
  235. drawCtx!.scale(dpr, dpr);
  236. // #endif
  237. // 填充背景色
  238. drawCtx!.fillStyle = props.backgroundColor;
  239. drawCtx!.fillRect(0, 0, props.width, props.height);
  240. emit("change");
  241. }
  242. // 获取签名图片
  243. function toPng(): Promise<string> {
  244. return canvasToPng({
  245. proxy,
  246. canvasId,
  247. canvasRef: canvasRef.value!
  248. });
  249. }
  250. // 初始化画布
  251. function initCanvas() {
  252. uni.createCanvasContextAsync({
  253. id: canvasId,
  254. component: proxy,
  255. success: (context: CanvasContext) => {
  256. // 获取绘图上下文
  257. drawCtx = context.getContext("2d")!;
  258. // 设置宽高
  259. drawCtx!.canvas.width = props.width;
  260. drawCtx!.canvas.height = props.height;
  261. // 优化渲染质量
  262. drawCtx!.textBaseline = "middle";
  263. drawCtx!.textAlign = "center";
  264. drawCtx!.miterLimit = 10;
  265. // 初始化背景
  266. clear();
  267. // #ifdef MP
  268. // 小程序中初始化时获取canvas位置信息
  269. getCanvasRect();
  270. // #endif
  271. }
  272. });
  273. }
  274. onMounted(() => {
  275. initCanvas();
  276. watch(
  277. computed(() => [props.width, props.height]),
  278. () => {
  279. initCanvas();
  280. }
  281. );
  282. });
  283. defineExpose({
  284. clear,
  285. toPng
  286. });
  287. </script>