Guest User

Signature

a guest
Oct 29th, 2024
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. 'use client'
  2.  
  3. import { useState, useRef, useEffect } from 'react'
  4. import { Button } from "@/components/ui/button"
  5. import { Label } from "@/components/ui/label"
  6. import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
  7.  
  8. export default function Component() {
  9. const [signature, setSignature] = useState<string | null>(null)
  10. const [isDrawing, setIsDrawing] = useState(false)
  11. const canvasRef = useRef<HTMLCanvasElement>(null)
  12.  
  13. useEffect(() => {
  14. const canvas = canvasRef.current
  15. if (canvas) {
  16. const ctx = canvas.getContext('2d')
  17. if (ctx) {
  18. ctx.lineWidth = 2
  19. ctx.lineCap = 'round'
  20. ctx.strokeStyle = 'black'
  21. }
  22. }
  23. }, [])
  24.  
  25. const startDrawing = (e: React.MouseEvent<HTMLCanvasElement>) => {
  26. setIsDrawing(true)
  27. draw(e)
  28. }
  29.  
  30. const stopDrawing = () => {
  31. setIsDrawing(false)
  32. const canvas = canvasRef.current
  33. if (canvas) {
  34. setSignature(canvas.toDataURL())
  35. }
  36. }
  37.  
  38. const draw = (e: React.MouseEvent<HTMLCanvasElement>) => {
  39. if (!isDrawing) return
  40. const canvas = canvasRef.current
  41. const ctx = canvas?.getContext('2d')
  42. if (ctx && canvas) {
  43. const rect = canvas.getBoundingClientRect()
  44. const x = e.clientX - rect.left
  45. const y = e.clientY - rect.top
  46. ctx.lineTo(x, y)
  47. ctx.stroke()
  48. ctx.beginPath()
  49. ctx.moveTo(x, y)
  50. }
  51. }
  52.  
  53. const clearSignature = () => {
  54. const canvas = canvasRef.current
  55. const ctx = canvas?.getContext('2d')
  56. if (ctx && canvas) {
  57. ctx.clearRect(0, 0, canvas.width, canvas.height)
  58. setSignature(null)
  59. }
  60. }
  61.  
  62. return (
  63. <Card className="w-full max-w-md mx-auto">
  64. <CardHeader>
  65. <CardTitle>Signature Pad</CardTitle>
  66. </CardHeader>
  67. <CardContent>
  68. <div className="space-y-2">
  69. <Label htmlFor="signature-pad">Signature</Label>
  70. <div className="border rounded-md p-2 bg-white">
  71. <canvas
  72. id="signature-pad"
  73. ref={canvasRef}
  74. width={400}
  75. height={200}
  76. onMouseDown={startDrawing}
  77. onMouseUp={stopDrawing}
  78. onMouseMove={draw}
  79. className="border rounded cursor-crosshair w-full"
  80. aria-label="Signature pad"
  81. />
  82. </div>
  83. </div>
  84. </CardContent>
  85. <CardFooter className="flex justify-between">
  86. <Button onClick={clearSignature} variant="outline">Clear Signature</Button>
  87. {signature && (
  88. <Button onClick={() => console.log(signature)}>Save Signature</Button>
  89. )}
  90. </CardFooter>
  91. </Card>
  92. )
  93. }
Advertisement
Add Comment
Please, Sign In to add comment