const canvas = document.createElement('canvas'); canvas.width = 280; canvas.height = 280; canvas.style.border = '1px solid black'; document.getElementById('canvasContainer').appendChild(canvas); const ctx = canvas.getContext('2d'); let isDrawing = false; let lastPredictionTime = 0; function initializeGrid() { ctx.strokeStyle = '#ddd'; for (let i = 0; i <= 28; i++) { ctx.beginPath(); ctx.moveTo(i * 10, 0); ctx.lineTo(i * 10, 280); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, i * 10); ctx.lineTo(280, i * 10); ctx.stroke(); } } function startDrawing(e) { isDrawing = true; draw(e); } function stopDrawing() { isDrawing = false; ctx.beginPath(); } function draw(e) { if (!isDrawing) return; ctx.lineWidth = 20; ctx.lineCap = 'round'; ctx.strokeStyle = '#000'; ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop); ctx.stroke(); ctx.beginPath(); ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop); // Check if it's time for a new prediction const currentTime = Date.now(); if (currentTime - lastPredictionTime > 1000) { // 1000ms = 1 second predictDrawing(); lastPredictionTime = currentTime; } } function predictDrawing() { const imageData = canvas.toDataURL('image/png').split(',')[1]; fetch('/predict', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({image: imageData}) }) .then(response => response.json()) .then(data => { document.getElementById('probability').textContent = `Probability: ${data.probability}`; }); } canvas.addEventListener('mousedown', startDrawing); canvas.addEventListener('mousemove', draw); canvas.addEventListener('mouseup', stopDrawing); canvas.addEventListener('mouseout', stopDrawing); document.getElementById('clearButton').addEventListener('click', () => { ctx.clearRect(0, 0, canvas.width, canvas.height); initializeGrid(); document.getElementById('probability').textContent = 'Probability: --'; }); initializeGrid();