簡體   English   中英

我可以檢測鼠標當前是否在畫布繪制功能內移動嗎?

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

我正在HTML5畫布中繪制一個矩形。 繪制時,我希望它是一種顏色(透明),繪制完后,我希望它是另一種顏色(不透明)。 我可以在繪圖函數中說出某種方式(也許使用條件)來檢測此時鼠標是否在移動嗎?

      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();
      }

更好的是,更改onleftmouseup的顏色。 但是,因為我要遍歷一個框架並覆蓋一個draw方法,所以如果可以在draw方法中進行操作會更好。 本身。 這可能嗎?

您需要將onmousedown和onmouseup事件偵聽器附加到canvas元素,該元素設置一個布爾值,該布爾值可以通過draw函數的作用域訪問。

就像是:

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)";
    }
    ...

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM