Priya
Priya

Reputation: 921

Canvas Drawing - why clickDrag.push(dragging) needed when we have x and y co-ords?

I came across below code while looking for canvas drawing. http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/

$('#canvas').mousedown(function(e){
     var mouseX = e.pageX - this.offsetLeft;
     var mouseY = e.pageY - this.offsetTop;

     paint = true;
     addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
     redraw();
   });

var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;

function addClick(x, y, dragging)
{
  clickX.push(x);
  clickY.push(y);
  clickDrag.push(dragging);
}
function redraw(){
  canvas.width = canvas.width; // Clears the canvas

  context.strokeStyle = "#df4b26";
  context.lineJoin = "round";
  context.lineWidth = 5;

  for(var i=0; i < clickX.length; i++)
  {     
    context.beginPath();
    if(clickDrag[i] && i){
      context.moveTo(clickX[i-1], clickY[i-1]);
     }else{
       context.moveTo(clickX[i]-1, clickY[i]);
     }
     context.lineTo(clickX[i], clickY[i]);
     context.closePath();
     context.stroke();
  }
}

When mousedown() event fires addClick() function is called by passing x and y values. (x and y co-ords). No value for var dragging is passed.

Then redraw() is called where if(clickDrag[i] && i){..} condition is tested.

My question is

1) how the clikDrag[] array is getting values and why is it needed when we have x and y co-ords.

2) What does the below code actually do? difference between clickX[i-1] and clickX[i]-1

if(clickDrag[i] && i){
          context.moveTo(clickX[i-1], clickY[i-1]);
         }else{
           context.moveTo(clickX[i]-1, clickY[i]);
         }

Upvotes: 0

Views: 288

Answers (1)

Jarrod
Jarrod

Reputation: 9465

1) As far as I can tell, it's not. "clickDrag" is adding the third param yet only 2 are given.

// two params passed
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);

function addClick(x, y, dragging) {
    ...
    clickDrag.push(dragging);
}

I'm guessing the addClick function is also called somewhere else, with this parameter

2) My guess is clickDrag is storing if the user is dragging or not. So if dragging, move to the next mouse pos (clickX[i-1] is referencing the mouse click position in the array, hence the -1 (array starts at 0))

If not dragging, the code is saying -1 from the result of array index i. I don't know the context of this call so cannot help you there, sorry.

EDIT-------------

So I downloaded the source and couldn't find the code you referenced in your second question. I found this, though:

    context.beginPath();
    if(clickDrag[i] && i){
        context.moveTo(clickX[i-1], clickY[i-1]);
    }else{
        context.moveTo(clickX[i], clickY[i]);
    }
    context.lineTo(clickX[i], clickY[i]);
    context.closePath();

Is it possible you accidently added the -1?

Upvotes: 0

Related Questions