Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use client'
- import { useState, useRef, useEffect } from 'react'
- import { Button } from "@/components/ui/button"
- import { Label } from "@/components/ui/label"
- import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
- export default function Component() {
- const [signature, setSignature] = useState<string | null>(null)
- const [isDrawing, setIsDrawing] = useState(false)
- const canvasRef = useRef<HTMLCanvasElement>(null)
- useEffect(() => {
- const canvas = canvasRef.current
- if (canvas) {
- const ctx = canvas.getContext('2d')
- if (ctx) {
- ctx.lineWidth = 2
- ctx.lineCap = 'round'
- ctx.strokeStyle = 'black'
- }
- }
- }, [])
- const startDrawing = (e: React.MouseEvent<HTMLCanvasElement>) => {
- setIsDrawing(true)
- draw(e)
- }
- const stopDrawing = () => {
- setIsDrawing(false)
- const canvas = canvasRef.current
- if (canvas) {
- setSignature(canvas.toDataURL())
- }
- }
- const draw = (e: React.MouseEvent<HTMLCanvasElement>) => {
- if (!isDrawing) return
- const canvas = canvasRef.current
- const ctx = canvas?.getContext('2d')
- if (ctx && canvas) {
- const rect = canvas.getBoundingClientRect()
- const x = e.clientX - rect.left
- const y = e.clientY - rect.top
- ctx.lineTo(x, y)
- ctx.stroke()
- ctx.beginPath()
- ctx.moveTo(x, y)
- }
- }
- const clearSignature = () => {
- const canvas = canvasRef.current
- const ctx = canvas?.getContext('2d')
- if (ctx && canvas) {
- ctx.clearRect(0, 0, canvas.width, canvas.height)
- setSignature(null)
- }
- }
- return (
- <Card className="w-full max-w-md mx-auto">
- <CardHeader>
- <CardTitle>Signature Pad</CardTitle>
- </CardHeader>
- <CardContent>
- <div className="space-y-2">
- <Label htmlFor="signature-pad">Signature</Label>
- <div className="border rounded-md p-2 bg-white">
- <canvas
- id="signature-pad"
- ref={canvasRef}
- width={400}
- height={200}
- onMouseDown={startDrawing}
- onMouseUp={stopDrawing}
- onMouseMove={draw}
- className="border rounded cursor-crosshair w-full"
- aria-label="Signature pad"
- />
- </div>
- </div>
- </CardContent>
- <CardFooter className="flex justify-between">
- <Button onClick={clearSignature} variant="outline">Clear Signature</Button>
- {signature && (
- <Button onClick={() => console.log(signature)}>Save Signature</Button>
- )}
- </CardFooter>
- </Card>
- )
- }
Advertisement
Add Comment
Please, Sign In to add comment