Tonor
Tonor

Reputation: 43

Draw line from one dot to another using mouse event

How can I use HTML5 canvas to simply connect two dots with one line using mouse? where I would click on the first dot and drag the mouse creating a line until it connects to the second dot. I have been using x/y offset to follow the mouse but drawing a line is where I need help in.

Data array is the two dots

$scope.data = [
     [192,27]
    ,[183,55]
  ];


  function drawDot(event) {
      if(dragging){

            context.lineTo(event.offsetX, event.offsetY);
            context.stroke();
            context.beginPath();
            context.arc(event.offsetX, event.offsetY,5, 0, Math.PI*2);
            context.fill();
            context.beginPath();
            context.moveTo(event.offsetX, event.offsetY);

        }
    }

  function engage(){
      dragging = true;
      drawDot(event);
  }

  function disengage(){
      dragging = false;
      context.beginPath(); 
  }

function init(){
    canvas.addEventListener("mousedown",engage);
    canvas.addEventListener("mouseup",disengage);
    canvas.addEventListener("mousemove",drawDot,false);
}

Upvotes: 0

Views: 2390

Answers (1)

QBM5
QBM5

Reputation: 2788

I am seeing a few things wrong here. Look at my example. I believe that is what you are looking for.

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d")


var startX = 0;
var startY = 0;

  function drawDot(event) {
      if(dragging){
      context.clearRect(0,0,canvas.width, canvas.height)
      context.beginPath();
      context.moveTo(startX, startY);
      context.lineTo(event.offsetX, event.offsetY);
       context.arc(event.offsetX, event.offsetY,5, 0, Math.PI*2);
      context.stroke();
      context.closePath();
        }
    }

  function engage(event){
      dragging = true;
      startX = event.offsetX;
      startY = event.offsetY;
  }

  function disengage(){
      dragging = false;
  }


canvas.addEventListener("mousedown",engage);
canvas.addEventListener("mouseup",disengage);
canvas.addEventListener("mousemove",drawDot,false);
<canvas id="canvas" style="margin: 10px; background: blue"></canvas>

Upvotes: 2

Related Questions