File size: 1,886 Bytes
d171e6f 24eec09 d171e6f 24eec09 d171e6f 24eec09 d171e6f 24eec09 d171e6f 24eec09 d171e6f |
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 |
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "white";
ctx.lineWidth = 16;
ctx.lineCap = "round";
let drawing = false;
// 滑鼠事件
canvas.addEventListener("mousedown", (e) => {
drawing = true;
draw(e.clientX, e.clientY);
});
canvas.addEventListener("mouseup", () => {
drawing = false;
ctx.beginPath();
});
canvas.addEventListener("mousemove", (e) => {
if (drawing) draw(e.clientX, e.clientY);
});
// 手機觸控事件
canvas.addEventListener("touchstart", (e) => {
e.preventDefault();
drawing = true;
const touch = e.touches[0];
draw(touch.clientX, touch.clientY);
});
canvas.addEventListener("touchmove", (e) => {
e.preventDefault();
if (drawing) {
const touch = e.touches[0];
draw(touch.clientX, touch.clientY);
}
});
canvas.addEventListener("touchend", () => {
drawing = false;
ctx.beginPath();
});
// 共用繪圖函式
function draw(x, y) {
const rect = canvas.getBoundingClientRect();
ctx.lineTo(x - rect.left, y - rect.top);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x - rect.left, y - rect.top);
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.fillRect(0, 0, canvas.width, canvas.height);
document.getElementById("result").innerText = "";
}
function submit() {
const image = canvas.toDataURL();
fetch("/predict", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ image })
})
.then(res => res.json())
.then(data => {
const text = `辨識結果:${data.label}\n信心值:${(data.confidence * 100).toFixed(2)}%`;
document.getElementById("result").innerText = text;
});
}
|