Files
Fixiy/Fixiy.Shared/wwwroot/js/signaturePad.js
T

79 lines
2.4 KiB
JavaScript

window.signaturePad = {
instances: {},
init(canvasId, dotNetRef) {
const canvas = document.getElementById(canvasId);
if (!canvas) return;
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#1a1a2e';
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
let drawing = false;
function getPos(e) {
const rect = canvas.getBoundingClientRect();
const src = e.touches ? e.touches[0] : e;
return {
x: (src.clientX - rect.left) * (canvas.width / rect.width),
y: (src.clientY - rect.top) * (canvas.height / rect.height)
};
}
function start(e) {
e.preventDefault();
drawing = true;
const pos = getPos(e);
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
}
function move(e) {
if (!drawing) return;
e.preventDefault();
const pos = getPos(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}
function end(e) {
if (!drawing) return;
drawing = false;
ctx.closePath();
if (dotNetRef) {
dotNetRef.invokeMethodAsync('OnSignatureChanged', canvas.toDataURL('image/png'));
}
}
canvas.addEventListener('mousedown', start);
canvas.addEventListener('mousemove', move);
canvas.addEventListener('mouseup', end);
canvas.addEventListener('mouseleave', end);
canvas.addEventListener('touchstart', start, { passive: false });
canvas.addEventListener('touchmove', move, { passive: false });
canvas.addEventListener('touchend', end);
this.instances[canvasId] = { canvas, ctx };
},
clear(canvasId) {
const instance = this.instances[canvasId];
if (!instance) return;
instance.ctx.clearRect(0, 0, instance.canvas.width, instance.canvas.height);
},
getDataUrl(canvasId) {
const instance = this.instances[canvasId];
return instance ? instance.canvas.toDataURL('image/png') : null;
},
isEmpty(canvasId) {
const instance = this.instances[canvasId];
if (!instance) return true;
const data = instance.ctx.getImageData(0, 0, instance.canvas.width, instance.canvas.height).data;
return !data.some(v => v !== 0);
}
};