鼠标事件:
function mouseEvent(type, sx, sy, cx, cy) {
var evt;
var e = {
bubbles: true,
cancelable: (type != "mousemove"),
view: window,
detail: 0,
screenX: sx,
screenY: sy,
clientX: cx,
clientY: cy,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
button: 0,
relatedTarget: undefined
};
if (typeof( document.createEvent ) == "function") {
evt = document.createEvent("MouseEvents");
evt.initMouseEvent(type,
e.bubbles, e.cancelable, e.view, e.detail,
e.screenX, e.screenY, e.clientX, e.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
e.button, document.body.parentNode);
} else if (document.createEventObject) {
evt = document.createEventObject();
for (prop in e) {
evt[prop] = e[prop];
}
evt.button = { 0:1, 1:4, 2:2 }[evt.button] || evt.button;
}
return evt;
}
function dispatchEvent (el, evt) {
if (el.dispatchEvent) {
el.dispatchEvent(evt);
} else if (el.fireEvent) {
el.fireEvent('on' + type, evt);
}
return evt;
}
用例:
var canvas = document.getElementsByTagName("canvas")[0];
var pageX = canvas.offsetLeft + (315 / 414) * canvas.offsetWidth;
var pageY = canvas.offsetTop + (30 / 600) * canvas.offsetHeight;
var event = mouseEvent("mousedown", pageX, pageY, pageX, pageY);
dispatchEvent(canvas, event);
var event = mouseEvent("mouseup", pageX, pageY, pageX, pageY);
dispatchEvent(canvas, event);
jquery版本:
var $canvas = $("#c2canvas");
var offset = $canvas.offset();
var restartPageX = offset.left + 0.5 * $canvas.width();
var restartPageY = offset.top + (408 / 435) * $canvas.height();
var e1 = new jQuery.Event("mousedown");
e1.pageX = restartPageX;
e1.pageY = restartPageY;
var e2 = new jQuery.Event("mouseup");
e2.pageX = restartPageX;
e2.pageY = restartPageY;
$(document).trigger(e1).trigger(e2);