所以,我正在尝试自动化一些图像标签,图像在画布上加载。他们需要触发鼠标事件在画布上做出一个点。我需要制作一个点击事件并在此画布上绘制一个矩形事件。尝试了下面的代码但没有成功。我错过了什么?
这个画布演示:https://accounts.hcaptcha.com/demo
function fireClickEvent(element) {
["mouseover", "mousedown", "mouseup", "click"].forEach((eventName) => {
if (element.fireEvent) {
element.fireEvent("on" + eventName);
} else {
const eventObject = document.createEvent("MouseEvents");
eventObject.initEvent(eventName, true, false);
element.dispatchEvent(eventObject);
}
});
}
function sendEventRectangleResponse(element, action, x, y) {
var eventTypes = {
down: "mousedown",
up: "mouseup",
move: "mousemove",
over: "mouseover",
out: "mouseout",
enter: "keydown",
};
var eventType = eventTypes[action];
if (!eventType) {
console.error("Invalid action provided");
return;
}
var canvas = document.querySelector(element);
if (!canvas || !(canvas instanceof HTMLElement)) {
console.error("Invalid canvas element");
return;
}
var event;
if (eventType === "keydown") {
event = new KeyboardEvent(eventType, {
bubbles: true,
cancelable: true,
key: "Enter",
keyCode: 13,
});
} else {
event = new MouseEvent(eventType, {
bubbles: true,
cancelable: true,
clientX: x,
clientY: y,
});
}
canvas.dispatchEvent(event);
}