canvas通过鼠标光标绘制线条

这是我通过按下/释放鼠标按钮在canvas中绘制线条的方式。 但这并不是我想要得到的:通过按下鼠标按钮,直线的起点就会设置,终点将跟随鼠标光标。 但是线条应该总是一条直线 – 而不是绘制一些曲线,就像现在这样做。 通过释放鼠标按钮,线完成/固定。

使用它应该能够在canvas上的任何位置绘制直线,任何方向/旋转。 按下鼠标按钮作为起点并释放直线终点。

$(function() { var letsdraw = false; var theCanvas = document.getElementById('paint'); var ctx = theCanvas.getContext('2d'); theCanvas.width = 420; theCanvas.height = 300; var canvasOffset = $('#paint').offset(); $('#paint').mousemove(function(e) { if (letsdraw === true) { ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top); ctx.stroke(); } }); $('#paint').mousedown(function() { letsdraw = true; ctx.strokeStyle = 'blue'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top); }); $(window).mouseup(function() { letsdraw = false; }); }); 
   

如果要修改它,你需要在canvas上擦除canvas上的内容
(使用ctx.clearRect() );

看看这个:

 $(function() { var letsdraw ; var theCanvas = document.getElementById('paint'); var ctx = theCanvas.getContext('2d'); theCanvas.width = 420; theCanvas.height = 300; var canvasOffset = $('#paint').offset(); $('#paint').mousemove(function(e) { if (letsdraw) { ctx.clearRect(0,0,theCanvas.width,theCanvas.height); ctx.strokeStyle = 'blue'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(letsdraw.x, letsdraw.y); ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top); ctx.stroke(); } }); $('#paint').mousedown(function(e) { letsdraw = { x:e.pageX - canvasOffset.left, y:e.pageY - canvasOffset.top } }); $(window).mouseup(function() { letsdraw = null; }); }); 
   

你应该这样做。

 $(function() { var letsdraw = false; var theCanvas = document.getElementById('paint'); var ctx = theCanvas.getContext('2d'); theCanvas.width = 420; theCanvas.height = 300; var canvasOffset = $('#paint').offset(); var lastpoints = { "x": 0, "y": 0 }; $('#paint').mousemove(function(e) { if (letsdraw === true) { lastpoints.x = e.pageX; lastpoints.y = e.pageY; } }); $('#paint').mousedown(function(e) { letsdraw = true; ctx.strokeStyle = 'blue'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top); }); $('#paint').mouseup(function(e) { ctx.lineTo(lastpoints.x - canvasOffset.left, lastpoints.y - canvasOffset.top); ctx.stroke(); letsdraw = false; }); });