# Day 8 瀏覽器上畫圖 比起上傳圖片,在瀏覽器上直接畫圖,直接上傳更加方便 所以在今天要做一個畫圖的功能 首先,把上傳的來源從暫存的 image 改成直接從 mycanvas 上拿。 mycanvas.toDataURL() 預設的格式也是 base64。 ```javascript= var mybutton = document.getElementById("mybutton"); mybutton.onclick = function () { base64_str = mycanvas.toDataURL(); $.post("/mnist", { "base64_str": base64_str }, function (data, status) { alert("Data: " + data + "\nStatus: " + status); console.log(data); }); } ``` 實作畫圖功能,因為需要的是黑底白字,所以開始時先把畫布塗黑。 以及實作滑鼠按下,移動,放開時的事件。 ```javascript= ctx.fillStyle = "#FFFFFF"; ctx.fillRect(0, 0, mycanvas.width, mycanvas.height); // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup mycanvas.addEventListener('mousedown', e => { x = e.offsetX; y = e.offsetY; isDrawing = true; }); mycanvas.addEventListener('mousemove', e => { if (isDrawing === true) { drawLine(ctx, x, y, e.offsetX, e.offsetY); x = e.offsetX; y = e.offsetY; } }); window.addEventListener('mouseup', e => { if (isDrawing === true) { drawLine(ctx, x, y, e.offsetX, e.offsetY); x = 0; y = 0; isDrawing = false; } }); function drawLine(context, x1, y1, x2, y2) { context.strokeStyle = "#FFFFFF"; context.fillStyle = "#FFFFFF"; context.beginPath(); context.lineWidth = 12; context.moveTo(x1, y1); context.lineTo(x2, y2); context.stroke(); ctx.fill(); context.closePath(); context.beginPath(); ctx.arc(x2, y2, 6, 0, 2 * Math.PI); ctx.fill(); context.closePath(); } ``` 結果 ![](https://i.imgur.com/qCQw1gh.mp4) 參考資料 https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event#examples