Javascript 如何在移动设备上画布绘图工作

Posted

技术标签:

【中文标题】Javascript 如何在移动设备上画布绘图工作【英文标题】:Javascript How to canvas drawing work on Mobile 【发布时间】:2021-12-28 23:55:11 【问题描述】:

我想做画布绘图,但此代码在移动浏览器上不起作用

const canvas = document.getElementById("draw");
    canvas.width = window.innerWidth - 60;
    canvas.height = 400;
    
    let context = canvas.getContext("2d");
    context.fillStyle = "white";
    context.fillRect(0, 0, canvas.width, canvas.height);
    
    let draw_color = "black";
    let draw_width = "2";
    let is_drawing = false;

    canvas.addEventListener("touchstart", start, false);
    canvas.addEventListener("touchmove", draw, false);
    canvas.addEventListener("mousedown", start, false);
    canvas.addEventListener("mousemove", draw, false);

    canvas.addEventListener("touchend", stop, false);
    canvas.addEventListener("mouseup", stop, false);
    canvas.addEventListener("mouseout", stop, false);


    function start(event) 
        is_drawing = true;
        context.beginPath();
        context.moveTo(event.clientX - canvas.offsetLeft,
                       event.clientY - canvas.offsetTop);
        event.preventDefault();
    

    
    function draw(event) 
        if (is_drawing) 
            context.lineTo(event.clientX - canvas.offsetLeft,
                           event.clientY - canvas.offsetTop);
            context.strokeStyle = draw_color;
            context.lineWidth = draw_width;
            context.lineCap = "round";
            context.lineJoin = "round";
            context.stroke();
        
        event.preventDefault();
    

    function stop(event) 
        if (is_drawing) 
            context.stroke();
            context.closePath();
            is_drawing = false;
        
        event.preventDefault();
    

【问题讨论】:

【参考方案1】:

试试这个

function draw(event) 
   e.preventDefault();
    e.stopPropagation();
    if (is_drawing) 
        context.lineTo(event.clientX - canvas.offsetLeft,
                       event.clientY - canvas.offsetTop);
        context.strokeStyle = draw_color;
        context.lineWidth = draw_width;
        context.lineCap = "round";
        context.lineJoin = "round";
        context.stroke();
    

【讨论】:

以上是关于Javascript 如何在移动设备上画布绘图工作的主要内容,如果未能解决你的问题,请参考以下文章

在 HTML5 画布上工作时出现 JavaScript (JQuery) 问题

如何在 HTML5 画布上绘图

记录和存储高分辨率手绘图

画布上的JavaScript事件在手机上

javascript 在页面上创建绘图画布

如何使fabricJS画布在移动设备上可水平拖动?