我正在开发一个涉及大型触摸面板的硬件项目,我想用它来控制 JS 应用程序中的鼠标事件。目前,我将面板连接到 Arduino Micro,它显示为 USB HID 设备,因此我可以将其视为鼠标,但这实际上不是该项目的理想解决方案。我的目标是让面板表现得像图形输入板一样,不管它是否实际上可能,这样我就可以将串行数据映射到显示器上的绝对坐标,然后在这些位置触发鼠标事件。我还想将该功能限制在浏览器内,而不是让它像鼠标一样在整个系统中运行,尽管这可能是次要问题。
据我所知,实际上用 JS 移动光标是不可能的(出于明显的安全原因)。我发现的最好的方法是 initmouseevent()
,不幸的是它在过去几年里似乎已经被贬值了。但事实上我并不需要真正移动鼠标;我想在 Canvas 内的特定位置触发各种行为,但这只是因为该应用程序当前正在查找鼠标事件,并且没有特殊原因它无法与不同的事件一起运行,只要它们提供适当的数据即可。
我包含了一些代码,但我的问题并不是特定于代码的。如果您有任何一般性建议,我将非常感激!
谢谢!!
当应用程序当前编写时,它会监听鼠标事件:
canvas.addEventListener('mousedown', this.onMouseDown.bind(this), false);
然后通过一系列函数传递事件:
onMouseDown: function (event) {
event.stopPropagation();
event.preventDefault();
this._gui.callFunc('onMouseDown', event);
this.onDeviceDown(event);
//console.log(event);
},
onDeviceDown: function (event) {
console.log("onDeviceDown " + JSON.stringify(event));
if (this._focusGui)
return;
this.setMousePosition(event);
//console.log("setMousePosition " + event);
var mouseX = this._mouseX;
var mouseY = this._mouseY;
var button = event.which;
var canEdit = false;
if (button === MOUSE_LEFT)
canEdit = this._sculpt.start(event.shiftKey);
if (button === MOUSE_LEFT && canEdit)
this.setCanvasCursor('none');
if (button === MOUSE_RIGHT && event.ctrlKey)
this._action = 'CAMERA_ZOOM';
else if (button === MOUSE_MIDDLE)
this._action = 'CAMERA_PAN';
else if (!canEdit && event.ctrlKey) {
this._maskX = mouseX;
this._maskY = mouseY;
this._action = 'MASK_EDIT';
} else if ((!canEdit || button === MOUSE_RIGHT) && event.altKey)
this._action = 'CAMERA_PAN_ZOOM_ALT';
else if (button === MOUSE_RIGHT || (button === MOUSE_LEFT && !canEdit))
this._action = 'CAMERA_ROTATE';
else
this._action = 'SCULPT_EDIT';
if (this._action === 'CAMERA_ROTATE' || this._action === 'CAMERA_ZOOM')
this._camera.start(mouseX, mouseY);
this._lastMouseX = mouseX;
this._lastMouseY = mouseY;
},
等等。
最佳答案
您可以使用 jQuery 并通过手动构建的 event
对象触发 mousedown
事件,设置 pageX、pageY、
和 其中
属于您自己。
https://api.jquery.com/category/events/event-object/
var e = new jQuery.Event("mousedown");
e.pageX = 10;
e.pageY = 10;
e.which = 3; // 1 for left button, 2 for middle, and 3 for right
$("#elem").trigger(e);
$("#elem")
将是您想要触发事件的页面元素,因此您可以在代码中使用类似 $(canvas)
的内容。
关于javascript - 使用 Javascript 和 Arduino 模拟鼠标事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960931/