Filipe Santos
Filipe Santos

Reputation: 1

calling a function with mouseevent

I have a drawing application in JavaScript to draw on the canvas. The tool below is the chalk tool.

Could someone let me know how I would call the function on mousedown event?

This is what I have tried:

$("#drawingCanvas").mousedown(function(ev) {
  tools.chalk.mousedown(ev);
});


var tools = {};

// Chalk tool.
tools.chalk = function() {
  var tool = this;
  this.started = false;

  // Begin drawing with chalk tool.
  this.mousedown = function(ev) {
    context.beginPath();
    context.moveTo(ev._x, ev._y);
    points.push({
      x: ev._x,
      y: ev._y,
      size: brushSize,
      color: brushColor,
      mode: "begin"
    });
    tool.started = true;
  };
  this.mousemove = function(ev) {
    if (tool.started) {
      context.lineTo(ev._x, ev._y);
      context.stroke();
      points.push({
        x: ev._x,
        y: ev._y,
        size: brushSize,
        color: brushColor,
        mode: "draw"
      });
    }
  };
  this.mouseup = function(ev) {
    if (tool.started) {
      tool.mousemove(ev);
      tool.started = false;
      points.push({
        x: ev._x,
        y: ev._y,
        size: brushSize,
        color: brushColor,
        mode: "end"
      });
      img_update();
    }
  };
};

Upvotes: 0

Views: 67

Answers (2)

Ele
Ele

Reputation: 33726

You're accessing an attribute called mousedown from the declared function chalk which is wrong because you're trying to access an attribute directly on the object chalk in this case a declared function.

I think what you really want to do is calling the function chalk as a constructor instead.

let tools = {};

// Chalk tool.
tools.chalk = function() {
  let tool = this;
  this.started = false;

  // Begin drawing with chalk tool.
  this.mousedown = function(ev) {
    console.log("mousedown");
  };  
};

let chalkObj = new tools.chalk();
$("#drawingCanvas").mousedown(function(ev) {
  chalkObj.mousedown(ev);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='drawingCanvas'>
<h1>CLICK ME</h1>
</div>

Upvotes: 1

Lucas
Lucas

Reputation: 301

just use DOM object delegation

$('.mouseDownDiv').on('mousedown' ,function(){
   console.log('mousedown!');
});
div{
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mouseDownDiv">Click here!</div>

Upvotes: 0

Related Questions