iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
AI & Data

機器學習與前端網頁系列 第 8

Day 8 瀏覽器上畫圖

比起上傳圖片,在瀏覽器上直接畫圖,直接上傳更加方便
所以在今天要做一個畫圖的功能

首先,把上傳的來源從暫存的 image 改成直接從 mycanvas 上拿。
mycanvas.toDataURL() 預設的格式也是 base64。

    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);
            });
    }

實作畫圖功能,因為需要的是黑底白字,所以開始時先把畫布塗黑。
以及實作滑鼠按下,移動,放開時的事件。

    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://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event#examples


上一篇
Day 7 拖動上傳圖片辨識數字
下一篇
day 9 打包 python 程式
系列文
機器學習與前端網頁30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言