使用鼠标按下和移动事件绘制直线的问题

Issue on Drawing Straight Line with Mouse Down and Move Event

能否请您看一下下面的演示,让我知道如何使代码能够在 canvas 上绘制 100% 直线?

$(function() {
    var drawLine = false;

    var theCanvas = document.getElementById('map');
    var ctx = theCanvas.getContext('2d');
    theCanvas.width = 420;
    theCanvas.height = 300;

    var canvasOffset = $('#map').offset();

    $('#map').mousemove(function(e) {
        if (drawLine === true) {
            ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
            ctx.stroke();
        }
    });

    $('#map').mousedown(function() {
        drawLine = true;
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 5;
        ctx.lineCap = 'round';
        ctx.beginPath();
        ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
    });

    $(window).mouseup(function() {
        drawLine = false;
    });
});
#map{border:solid; margin-top: 50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<canvas id="map"></canvas>

如您所见,代码运行良好,但我想要的是在绘图上画一条直线

谢谢

您需要 2 个 canvases:

  1. 临时动画
  2. 永久保存绘图。

算法:

  1. ondown写入起始坐标。
  2. onmove记录端点,清除canvas1,在canvas1上从起点到终点画一条线
  3. onup 在第 2 画最后一行 canvas 清除第 1 canvas。

懒得创​​建第二个canvas(现在每次尝试都会清除它); 在 pass different canvas for permanent draw

的地方发表评论

$(function() {
    var drawLine = false;

    var theCanvas = document.getElementById('map');
    var finalPos = {x:0, y:0};
    var startPos = {x:0, y:0};
    var ctx = theCanvas.getContext('2d');
    theCanvas.width = 420;
    theCanvas.height = 300;

    var canvasOffset = $('#map').offset();

    function line(cnvs) {
        cnvs.beginPath();
        cnvs.moveTo(startPos.x, startPos.y);
        cnvs.lineTo(finalPos.x, finalPos.y);
        cnvs.stroke();
    }

    function clearCanvas()
    {
       ctx.clearRect(0, 0, theCanvas.width, theCanvas.height);
    }

    $('#map').mousemove(function(e) {
        if (drawLine === true) {
            finalPos = {x: e.pageX - canvasOffset.left, y:e.pageY - canvasOffset.top};

            clearCanvas();
            line(ctx);
            
        }
    });

    $('#map').mousedown(function(e) {
        drawLine = true;
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 5;
        ctx.lineCap = 'round';
        ctx.beginPath();
        startPos = { x: e.pageX - canvasOffset.left, y: e.pageY - canvasOffset.top};
    });

    $(window).mouseup(function() {
        clearCanvas();
        // Replace with var that is second canvas
        line(ctx);
        finalPos = {x:0, y:0};
        startPos = {x:0, y:0};
        drawLine = false;
    });
});
#map{border:solid; margin-top: 50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<canvas id="map"></canvas>