简体   繁体   中英

Can I detect if the mouse is currently moving inside a canvas draw function?

I am drawing a rectangle in HTML5 canvas. I want it to be one color (transparent) when I am drawing it, and then another color (opaque) when I am done drawing it. Is there a way that I can say in my draw function, maybe using a conditional, to detect if the mouse is moving at this moment? ie

      draw: function(ctx) {

          ctx.beginPath();
          ctx.rect(this.X, this.Y, this.Width, this.Height);
          if(mouseisMoving) {
              ctx.fillStyle = "rgba(0,0,0,1)";
          }
          else {
          ...
          }
          ctx.fill();
          ctx.stroke();
      }

Even better, change the color onleftmouseup. However, because I am going through a framework and overriding a draw method, it would be better if I could do it inside the draw method. Itself. Is this possible?

You'll want to attach an onmousedown and onmouseup event listener to your canvas element that sets a boolean that's accessible by the scope of your draw function.

Something like:

var mouse = false;

canvas.onmousedown = function () {
    mouse = true;
};

canvas.onmouseup = function () {
    mouse = false;
};

var draw = function (ctx) {
    if (mouse) {
        ctx.fillStyle = "rgba(0,0,0,1)";
    }
    ...

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM