forked from fahrPool/fahrPool
79 lines
2.2 KiB
TypeScript
79 lines
2.2 KiB
TypeScript
"use client";
|
|
|
|
import { useRef, useState } from "react";
|
|
|
|
export function UnterschriftCanvas({ name }: { name: string }) {
|
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
|
const zeichnetRef = useRef(false);
|
|
const [hatInhalt, setHatInhalt] = useState(false);
|
|
const [dataUrl, setDataUrl] = useState("");
|
|
|
|
function getPos(event: React.PointerEvent<HTMLCanvasElement>) {
|
|
const rect = event.currentTarget.getBoundingClientRect();
|
|
return { x: event.clientX - rect.left, y: event.clientY - rect.top };
|
|
}
|
|
|
|
function onPointerDown(event: React.PointerEvent<HTMLCanvasElement>) {
|
|
const canvas = canvasRef.current;
|
|
if (!canvas) return;
|
|
canvas.setPointerCapture(event.pointerId);
|
|
zeichnetRef.current = true;
|
|
const ctx = canvas.getContext("2d");
|
|
const { x, y } = getPos(event);
|
|
ctx?.beginPath();
|
|
ctx?.moveTo(x, y);
|
|
}
|
|
|
|
function onPointerMove(event: React.PointerEvent<HTMLCanvasElement>) {
|
|
if (!zeichnetRef.current) return;
|
|
const canvas = canvasRef.current;
|
|
const ctx = canvas?.getContext("2d");
|
|
if (!ctx) return;
|
|
const { x, y } = getPos(event);
|
|
ctx.lineWidth = 2;
|
|
ctx.lineCap = "round";
|
|
ctx.strokeStyle = "#1a1a1a";
|
|
ctx.lineTo(x, y);
|
|
ctx.stroke();
|
|
setHatInhalt(true);
|
|
}
|
|
|
|
function onPointerUp() {
|
|
zeichnetRef.current = false;
|
|
const canvas = canvasRef.current;
|
|
if (canvas) {
|
|
setDataUrl(canvas.toDataURL("image/png"));
|
|
}
|
|
}
|
|
|
|
function loeschen() {
|
|
const canvas = canvasRef.current;
|
|
const ctx = canvas?.getContext("2d");
|
|
if (canvas && ctx) {
|
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
}
|
|
setHatInhalt(false);
|
|
setDataUrl("");
|
|
}
|
|
|
|
return (
|
|
<div className="mb-4">
|
|
<canvas
|
|
ref={canvasRef}
|
|
width={320}
|
|
height={160}
|
|
onPointerDown={onPointerDown}
|
|
onPointerMove={onPointerMove}
|
|
onPointerUp={onPointerUp}
|
|
className="touch-none w-full rounded-md border border-aluminium-grey bg-white"
|
|
/>
|
|
<input type="hidden" name={name} value={dataUrl} />
|
|
{hatInhalt && (
|
|
<button type="button" onClick={loeschen} className="mt-2 text-sm text-performance-blue hover:underline">
|
|
Unterschrift löschen
|
|
</button>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|