Bula
Bula

Reputation: 2792

Canvas alert when the user moves and holds down mouse

I'm trying to build a simple script which console logs me whenever the user holds and moves the mouse inside my canvas:

   <!DOCTYPE HTML>
<html>
<head>

</head>

<body>


<script>
window.onload = function(){
var c = document.getElementById("myCanvas");
var moving = false;
console.log(c);
 var ctx = c.getContext("2d");
c.onMouseDown = function(evt){
moving = true
};
c.onMouseMove = function(){
    if(moving == true)
    {
        console.log("holding and moving");
    }
};
c.onMouseUp = function(evt){
    moving = false;
};
};

</script>
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
</body>


</html>

However whenever I hold and move there is no console log. What am I missing in my logic here?

Upvotes: 0

Views: 40

Answers (1)

markE
markE

Reputation: 105015

A couple of glitches:

  • close the html tag
  • no capitals when defining onmousedown, onmousemove, onmouseup

Fixed code:

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<script>
window.onload = function(){

    var c = document.getElementById("myCanvas");
    var moving = false;
    console.log(c);
    var ctx = c.getContext("2d");

    c.onmousedown = function(evt){
    moving = true
    };

    c.onmousemove = function(){
        if(moving == true)
        {
            console.log("holding and moving");
        }
    };

    c.onmouseup = function(evt){
        moving = false;
    };

};

</script>
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
</body>
</html>

Upvotes: 2

Related Questions