49 lines
2.5 KiB
Vue
49 lines
2.5 KiB
Vue
<template>
|
||
<div class="aa-sign">
|
||
<div class="aa-sign-pad" ref="pad">
|
||
<canvas ref="canvas" class="aa-sign-canvas" @mousedown="down" @mousemove="move" @mouseup="up" @touchstart="down" @touchmove="move" @touchend="up"></canvas>
|
||
<div class="aa-sign-placeholder" v-show="!hasInk">请在此处签名</div>
|
||
</div>
|
||
<div class="aa-sign-actions">
|
||
<button class="aa-btn" @click="undo">撤销</button>
|
||
<button class="aa-btn" @click="clear">清除</button>
|
||
<button class="aa-btn aa-btn--primary" @click="save">保存</button>
|
||
<span class="aa-sign-preview" v-if="saved">{{ saved }}</span>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup>
|
||
import { ref, onMounted, onBeforeUnmount } from 'vue';
|
||
|
||
const pad = ref(null);
|
||
const canvas = ref(null);
|
||
const drawing = ref(false);
|
||
const last = ref(null);
|
||
const strokes = ref([]);
|
||
const cur = ref([]);
|
||
const hasInk = ref(false);
|
||
const saved = ref('');
|
||
|
||
function ctx() { return canvas.value.getContext('2d'); }
|
||
function fit() { var r = pad.value.getBoundingClientRect(); canvas.value.width = r.width; canvas.value.height = r.height; redraw(); }
|
||
function pos(e) { var r = canvas.value.getBoundingClientRect(); var t = e.touches && e.touches[0]; return { x: (t ? t.clientX : e.clientX) - r.left, y: (t ? t.clientY : e.clientY) - r.top }; }
|
||
function down(e) { e.preventDefault(); drawing.value = true; last.value = pos(e); cur.value = [last.value]; strokes.value.push(cur.value); hasInk.value = true; }
|
||
function move(e) { if (!drawing.value) return; e.preventDefault(); var p = pos(e); ctx().lineTo(p.x, p.y); ctx().stroke(); cur.value.push(p); }
|
||
function up() { drawing.value = false; last.value = null; }
|
||
function undo() { strokes.value.pop(); redraw(); if (!strokes.value.length) hasInk.value = false; }
|
||
function clear() { strokes.value = []; redraw(); hasInk.value = false; saved.value = ''; }
|
||
function save() { saved.value = '已导出(' + canvas.value.width + '×' + canvas.value.height + ')'; }
|
||
function redraw() {
|
||
var c = canvas.value, x = c.getContext('2d');
|
||
x.clearRect(0, 0, c.width, c.height);
|
||
x.strokeStyle = '#1F2329'; x.lineWidth = 2; x.lineCap = 'round'; x.lineJoin = 'round';
|
||
strokes.value.forEach(function (s) { x.beginPath(); s.forEach(function (p, i) { i ? x.lineTo(p.x, p.y) : x.moveTo(p.x, p.y); }); x.stroke(); });
|
||
}
|
||
|
||
onMounted(() => { fit(); window.addEventListener('resize', fit); });
|
||
onBeforeUnmount(() => window.removeEventListener('resize', fit));
|
||
</script>
|
||
|
||
<style src="./SignaturePad.css"></style>
|