在移动设备上画布javascript事件



我实际上触发了所有这些事件,但它们似乎都不适用于移动设备。画布实际上是720x1000px,并没有覆盖所有页面。

canvas.addEventListener('mousedown', alert);
canvas.addEventListener('mousemove', alert);
canvas.addEventListener('mouseup',   alert);
canvas.addEventListener("touchstart", alert);
canvas.addEventListener("touchend", alert);
canvas.addEventListener("touchmove", alert);
canvas.addEventListener("pointerup", alert);
canvas.addEventListener("pointerdown", alert);
canvas.addEventListener("pointermove", alert);

问题是由事件监听器引起的还是由画布引起的?我该如何解决?

仅在移动设备上?

从桌面检查它时,当您运行它&触发任何事件,就会抛出以下错误:

TypeError: 'alert' called on an object that does not implement interface Window.


问题是,你的alert是什么?

  1. 如果它是您定义并调用alert()的自定义函数,最好更改名称,因为它已经存在,它是Window接口的一个方法
  2. 如果这意味着alert((,那么它就不是对函数,并且需要将引用作为回调传递给函数。如果您想调用它,您需要将它封装在一个函数引用(匿名或命名的函数引用(中,并将其作为回调传递

在事件侦听器中设置回调的不同方式

  • 通过匿名函数:

    canvas.addEventListener('mousemove', function(){
    alert('This is an alert');
    });
    

const canvas = document.getElementById('canvas');
canvas.addEventListener('mousemove', function(){
alert('This is an alert');
});
#canvas{
background-color: green;
}
<canvas id="canvas" width="100" height="100"></canvas>

  • 通过命名函数(带有匿名函数(:

    function doAlert(msg){
    return function () {
    alert(msg);
    };
    }
    canvas.addEventListener('mousemove', doAlert('This is an alert'));
    

const canvas = document.getElementById('canvas');
function doAlert(msg){
return function () {
alert(msg);
};
}
canvas.addEventListener('mousemove', doAlert('This is an alert'));
#canvas{
background-color: green;
}
<canvas id="canvas" width="100" height="100"></canvas>

  • 通过命名函数(使用bind((方法(:

    function doAlert(msg){
    return alert(msg);
    }
    canvas.addEventListener('mousemove', doAlert.bind(null, 'This is an alert'));
    

const canvas = document.getElementById('canvas');
function doAlert(msg){
return alert(msg);
}
canvas.addEventListener('mousemove', doAlert.bind(null, 'This is an alert'));
#canvas{
background-color: green;
}
<canvas id="canvas" width="100" height="100"></canvas>

相关内容

  • 没有找到相关文章

最新更新