| 61 | }; |
| 62 | |
| 63 | const generateCode = async () => { |
| 64 | setIsGenerating(true); |
| 65 | |
| 66 | try { |
| 67 | // In a real implementation, this would send the canvas data to an API |
| 68 | // For now, we'll simulate with a timeout |
| 69 | await new Promise((resolve) => setTimeout(resolve, 1500)); |
| 70 | |
| 71 | // Get canvas data |
| 72 | const canvas = canvasRef.current; |
| 73 | const _dataUrl = canvas.toDataURL("image/png"); |
| 74 | |
| 75 | // Simulate code generation based on the drawing |
| 76 | const mockCode = `// Generated code from your drawing |
| 77 | function drawPattern() { |
| 78 | const canvas = document.getElementById('myCanvas'); |
| 79 | const ctx = canvas.getContext('2d'); |
| 80 | |
| 81 | // Set background |
| 82 | ctx.fillStyle = '#ffffff'; |
| 83 | ctx.fillRect(0, 0, canvas.width, canvas.height); |
| 84 | |
| 85 | // Draw your pattern |
| 86 | ctx.strokeStyle = '${color}'; |
| 87 | ctx.lineWidth = ${brushSize}; |
| 88 | ctx.lineCap = 'round'; |
| 89 | |
| 90 | // Add your drawing logic here |
| 91 | // This is a placeholder for your actual drawing |
| 92 | ctx.beginPath(); |
| 93 | ctx.moveTo(50, 50); |
| 94 | ctx.lineTo(200, 100); |
| 95 | ctx.stroke(); |
| 96 | |
| 97 | ctx.beginPath(); |
| 98 | ctx.arc(150, 150, 50, 0, 2 * Math.PI); |
| 99 | ctx.stroke(); |
| 100 | } |
| 101 | |
| 102 | // Call the function to draw |
| 103 | drawPattern();`; |
| 104 | |
| 105 | setGeneratedCode(mockCode); |
| 106 | setShowCode(true); |
| 107 | onCodeGenerated(mockCode); |
| 108 | } catch (error) { |
| 109 | console.error("Error generating code:", error); |
| 110 | setGeneratedCode("// Error generating code. Please try again."); |
| 111 | setShowCode(true); |
| 112 | // Show toast notification for error |
| 113 | if (window?.showToast) |
| 114 | window.showToast( |
| 115 | `Error generating code: ${error.message}`, |
| 116 | "error", |
| 117 | ); |
| 118 | } finally { |
| 119 | setIsGenerating(false); |
| 120 | } |