当用户移动并按住鼠标时,画布会发出警报

时间:2014-02-25 21:17:22

标签: javascript html5 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>

然而,每当我按住并移动时,都没有控制台日志。我的逻辑中缺少什么?

1 个答案:

答案 0 :(得分:2)

一些小故障:

  • 关闭html标记
  • 定义onmousedown,onmousemove,onmouseup
  • 时没有大写字母

固定代码:

<!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>