javascript 在画布 html5 页面上模拟鼠标上下移动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18365187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:38:44  来源:igfitidea点击:

simulate a mouse down and up on a canvas html5 page

javascriptasp.nethtml

提问by Philo

How can I simulate a mouse down and then followed by a mouse up event on a canvas hmtl5 section of an aspx page?

如何在 aspx 页面的画布 hmtl5 部分模拟鼠标按下,然后是鼠标按下事件?

I searched on the web and found this... but i cannot correlate this to my canvas html5 element, Can anyone help ?

我在网上搜索并找到了这个……但我无法将它与我的画布 html5 元素相关联,有人可以帮忙吗?

dispatchMouseEvent(element, 'mouseover', true, true);
dispatchMouseEvent(element, 'mousedown', true, true);
dispatchMouseEvent(element, 'click', true, true);
dispatchMouseEvent(element, 'mouseup', true, true);

回答by user2701675

"Simulating" events is very easy, in fact, you can simply trigger them. Using jQuery, this becomes child's play (see this jsfiddlefor working example):

“模拟”事件非常容易,实际上,您可以简单地触发它们。使用 jQuery,这就变成了孩子的游戏(参见这个 jsfiddle的工作示例):

$('#canvas_element').on("mousedown mouseup", function(e) {
console.log(e.type + " event fired at coords: " + e.pageX + ", " + e.pageY);
});

x_coord = 1;
y_coord = 1;

var e = jQuery.Event( "mousedown", { pageX: x_coord, pageY: y_coord } );
$('#canvas_element').trigger(e);

// execute more code
x_coord = 255;
y_coord = 255;

var e = jQuery.Event( "mouseup", { pageX: x_coord, pageY: y_coord } );
$('#canvas_element').trigger(e);

See this old SO questionfor a pure javascript solution.

有关纯 javascript 解决方案,请参阅这个旧的 SO 问题