1
0
Fork 0
fahrPool/web/components/auftraege/UnterschriftCanvas.tsx

155 lines
5.1 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
export function UnterschriftCanvas({ name }: { name: string }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const zeichnetRef = useRef(false);
// hatInhaltRef spiegelt hatInhalt synchron wider, damit onPointerUp
// (kein Re-Render dazwischen) zuverlaessig weiss, ob wirklich gezeichnet
// wurde.
const hatInhaltRef = useRef(false);
const [hatInhalt, setHatInhalt] = useState(false);
const [dataUrl, setDataUrl] = useState("");
// Setzt die Bitmap-Aufloesung des Canvas auf die tatsaechlich dargestellte
// CSS-Groesse * devicePixelRatio und skaliert den 2D-Context so, dass in
// CSS-Pixeln gezeichnet werden kann. Ohne das rendert das Element (w-full)
// breiter als seine 320px-Bitmap: der Finger zeichnet versetzt und der
// rechte Teil der Unterschrift landet ausserhalb der Bitmap. Wird beim
// Mount und bei jedem Resize aufgerufen; vorhandene Zeichnung wird dabei
// skaliert uebernommen.
const canvasSkalieren = useCallback(() => {
if (typeof window === "undefined") return;
const canvas = canvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return;
const dpr = window.devicePixelRatio || 1;
const zielBreite = Math.round(rect.width * dpr);
const zielHoehe = Math.round(rect.height * dpr);
if (canvas.width === zielBreite && canvas.height === zielHoehe) return;
const altBreite = canvas.width;
const altHoehe = canvas.height;
const altCtx = canvas.getContext("2d");
let vorschau: HTMLCanvasElement | null = null;
if (altCtx && altBreite > 0 && altHoehe > 0 && hatInhaltRef.current) {
vorschau = document.createElement("canvas");
vorschau.width = altBreite;
vorschau.height = altHoehe;
vorschau.getContext("2d")?.drawImage(canvas, 0, 0);
}
canvas.width = zielBreite;
canvas.height = zielHoehe;
const ctx = canvas.getContext("2d");
if (!ctx) return;
if (vorschau) {
// In Geraetepixeln zeichnen, bevor der Massstab gesetzt wird.
ctx.drawImage(vorschau, 0, 0, altBreite, altHoehe, 0, 0, zielBreite, zielHoehe);
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.strokeStyle = "#1a1a1a";
}, []);
useEffect(() => {
canvasSkalieren();
window.addEventListener("resize", canvasSkalieren);
return () => window.removeEventListener("resize", canvasSkalieren);
}, [canvasSkalieren]);
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.lineJoin = "round";
ctx.strokeStyle = "#1a1a1a";
ctx.lineTo(x, y);
ctx.stroke();
if (!hatInhaltRef.current) {
hatInhaltRef.current = true;
setHatInhalt(true);
}
}
function onPointerUp() {
zeichnetRef.current = false;
// Nur wenn wirklich ein Strich gezeichnet wurde, wird das versteckte
// Feld mit einer Data-URL befuellt. Ein unberuehrtes Canvas oder ein
// versehentliches Antippen (Down + Up ohne Bewegung) laesst den Wert
// "" -> fahrtBeenden ueberspringt den Upload.
if (!hatInhaltRef.current) return;
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.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
}
hatInhaltRef.current = false;
setHatInhalt(false);
setDataUrl("");
}
return (
<div className="mb-4">
<canvas
id="unterschrift-canvas"
ref={canvasRef}
width={320}
height={160}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
className="h-40 w-full touch-none rounded-md border border-aluminium-grey bg-white"
/>
<input type="hidden" name={name} value={dataUrl} />
{hatInhalt && (
<button
type="button"
onClick={loeschen}
className="mt-2 inline-flex min-h-11 items-center text-sm text-performance-blue hover:underline"
>
Unterschrift löschen
</button>
)}
</div>
);
}