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


<<:  【Day8】ERP核心模组篇-Invoicing

>>:  08 - Metrics - 观察系统的健康指标 (2/6) - 使用 Metricbeat 掌握 Elastic Stack 的健康状态

JS 32 - 资料丢进来,就能计算所需样本数量!

大家好! 今天要接续 JS 30 的内容。 我们进入今天的主题吧! 程序码 function par...

30天轻松学会unity自制游戏-让Player动起来

按照之前的进度制作,现在按下▶Player应该会魔性地扭动起来,但就没有其他效果了,接下来就改造Pl...

予焦啦!Hello World 与 Uart 机制观察

本节是以 Golang 上游 7ee4c1665477c6cf574cb9128deaf9d009...

[Day 14] - 初探永丰银行线上收款API - 丰收款 - HASH ID计算(1)

接续昨天 根据规格书,我们要用永丰提供的四组hash值拼出hash id 可以看出,hash id会...

DAY 21 - 四足战车 (2)

大家好~ 我是五岁~ 今天来画四足战车的草图细节~ 首先来画上半部 依照昨天的外型草稿,进一步认真的...