Skip to content
Advertisement

Making sure I get a mouse up event for every mouse down

The code below draws a rectangle on every mouse move after the mouse button is pressed. When the user releases the mouse it should stop drawing.

I am trying to figure out how to make sure that drawing stops if the user releases the mouse outside the canvas element.

I thought that I could accomplish this by setting onmouseup event handler on my event inside onmousedown like this:

canvas.onmousedown = function (e) {
  drawing = true;
  e.onmouseup = function (v) { drawing = false; }
};
but it did not work because e.onmouseup is never called. So I ended up setting window.onmouseup instead.

Questions:

  1. why was my e.onmouseup never called?
  2. is my final solution the best way to do it?

<!DOCTYPE HTML>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <script type="text/javascript">
      drawing = false;
function on_load(e) { var canvas = document.getElementById("canvas");
canvas.onmousedown = function (e) { drawing = true; };
canvas.onmousemove = function (e) { if (drawing) { var x = e.pageX - canvas.offsetLeft; var y = e.pageY - canvas.offsetTop; var context = canvas.getContext("2d"); context.strokeRect(x, y, 10, 10); } };
window.onmouseup = function (e) { drawing = false; }; } </script> </head> <body onload="on_load()"> <canvas id="canvas" width="500" height="500" style="border: 1px solid black;"> </canvas> </body> </html>

Advertisement

Answer

  1. Why was my e.onmouseup never called?

e is an Event object. It doesn’t have a defined behaviour for an onmouseup property

  2. Is my final solution the best way to do it?

Yes, but with some adjustments. First, consider if you really need the global variable. The same effect can be achieved without the global variable, but it might useful to keep it global for debugging purposes.

Second, your not-working code is not needed. It’s better to have one always-existing event listener which only changes a harmless variable, than constructing a new event listener for each mouseup event. Besides, in your “wanted” code, the previous mouseup event is never explicitly removed.

 function on_load(e) {
    var drawing = false; // <-- Always declare variables
    var canvas = document.getElementById("canvas");
    canvas.onmousedown = function (e) { drawing = true; };
    canvas.onmousemove = function (e) {
      if (drawing) {
        var x = e.pageX - canvas.offsetLeft;
        var y = e.pageY - canvas.offsetTop;
        var context = canvas.getContext("2d");
        context.strokeRect(x, y, 10, 10);
      }
    };
    window.onmouseup = function (e) { drawing = false; };
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement