Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas draw line by following mouse cursor

This is how I'm drawing a line in a canvas by pressing/releasing the mouse button. But it is not exactly what I try to get: By pressing the mouse button the starting point of a stright line is beeing set, the end point will follow the mouse cursor. But the line should be always a straight line - not drawing of some curves, like it is be done now. By releasing the mouse button the line is finished/fixed.

With that the use should be able to draw straight line anywhere on the canvas with any orientation/rotation. Pressing mouse button for starting point and releasing for end point of a straight line.

$(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;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="paint"></canvas>
like image 752
user3142695 Avatar asked Feb 08 '23 20:02

user3142695


1 Answers

you need to erase what's on the canvas once it's painted if you want to modify it
( with ctx.clearRect() );

take a look at this:

$(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;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="paint"></canvas>
like image 134
maioman Avatar answered Feb 10 '23 23:02

maioman