Spaces:
Sleeping
Sleeping
File size: 2,174 Bytes
0854d0c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
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();
|