1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| <template> <div class="signature-pad" :style="{ width: props.width, height: props.height }" > <canvas ref="canvas"></canvas> <slot> <button @click="clearSignature">清除簽名</button> <button @click="saveSignature">儲存簽名</button> </slot> </div> </template>
<script setup> import { onMounted, ref, watch, onUnmounted } from "vue"; import SignaturePad from "signature_pad";
const props = defineProps({ width: { type: String, default: "100%" }, height: { type: String, default: "300px" }, penColor: { type: String, default: "black" }, backgroundColor: { type: String, default: "white" }, options: { type: Object, default: () => ({}) }, });
const canvas = ref(null); let signaturePad = null;
const initializeSignaturePad = () => { if (canvas.value) { signaturePad = new SignaturePad(canvas.value, { ...props.options, penColor: props.penColor, backgroundColor: props.backgroundColor, }); } };
const resizeCanvas = () => { const ratio = Math.max(window.devicePixelRatio || 1, 1); canvas.value.width = canvas.value.offsetWidth * ratio; canvas.value.height = canvas.value.offsetHeight * ratio; canvas.value.getContext("2d").scale(ratio, ratio); signaturePad.clear(); };
const emit = defineEmits(["clear", "save"]);
const saveSignature = () => { if (signaturePad) { const signatureImage = signaturePad.toDataURL(); emit("save", signatureImage); } return null; };
const clearSignature = () => { if (signaturePad) { signaturePad.clear(); emit("clear"); } };
onMounted(() => { initializeSignaturePad(); window.addEventListener("resize", resizeCanvas); resizeCanvas(); });
onUnmounted(() => { window.removeEventListener("resize", resizeCanvas); });
watch( () => [props.penColor, props.backgroundColor, props.options], () => { initializeSignaturePad(); }, { deep: true } ); </script>
|