我有外部html5画布,您可以使用鼠标在某些行上绘画。我想以编程方式绘制此画布的内容,例如圆圈但是以动画的形式出现(不是一次性绘画,而是模仿人类的行为方式,画出圆圈让我们说持续1秒。
外部代码不是我的,并使用GWT,这种方式是高度压缩和混淆的。这就是我考虑触发一系列mousedown, mousemove, sleep, mousemove, mouseup
事件的原因。我知道可以触发鼠标向下和向上事件但是在特定位置的鼠标移动事件呢?理想情况下使用jquery。
答案 0 :(得分:3)
您是否查看了initMouseEvent
和dispatchEvent
?
这是一个链接https://developer.mozilla.org/en/Document_Object_Model_%28DOM%29/event.initMouseEvent
答案 1 :(得分:1)
执行此操作的新(不推荐)方法是使用MouseEvent
构造函数。
以下是一些可以适应您的用例的示例代码:
var gestureTimeoutID;
var periodicGesturesTimeoutID;
window.simulateRandomGesture = function (doneCallback) {
var target = document.querySelector('canvas');
var rect = target.getBoundingClientRect();
var simulateMouseEvent = function simulateMouseEvent(type, point) {
var event = new MouseEvent(type, {
'view': window,
'bubbles': true,
'cancelable': true,
'clientX': rect.left + point.x,
'clientY': rect.top + point.y,
// you can pass any other needed properties here
});
target.dispatchEvent(event);
};
var t = 0;
/* Simple circle:
var getPointAtTime = (t) => {
return {
x: 300 + Math.sin(t / 50) * 150,
y: 300 + Math.cos(t / 50) * 150,
};
};
*/
// More fun:
var cx = Math.random() * rect.width;
var cy = Math.random() * rect.height;
var gestureComponents = [];
var numberOfComponents = 5;
for (var i = 0; i < numberOfComponents; i += 1) {
gestureComponents.push({
rx: Math.random() * Math.min(rect.width, rect.height) / 2 / numberOfComponents,
ry: Math.random() * Math.min(rect.width, rect.height) / 2 / numberOfComponents,
angularFactor: Math.random() * 5 - Math.random(),
angularOffset: Math.random() * 5 - Math.random()
});
}
var getPointAtTime = function getPointAtTime(t) {
var point = { x: cx, y: cy };
for (var i = 0; i < gestureComponents.length; i += 1) {
var c = gestureComponents[i];
point.x += Math.sin(Math.PI * 2 * (t / 100 * c.angularFactor + c.angularOffset)) * c.rx;
point.y += Math.cos(Math.PI * 2 * (t / 100 * c.angularFactor + c.angularOffset)) * c.ry;
}
return point;
};
simulateMouseEvent('mousedown', getPointAtTime(t));
var move = function move() {
t += 1;
if (t > 50) {
simulateMouseEvent('mouseup', getPointAtTime(t));
if (doneCallback) {
doneCallback();
}
} else {
simulateMouseEvent('mousemove', getPointAtTime(t));
gestureTimeoutID = setTimeout(move, 10);
}
};
move();
};
window.simulateRandomGesturesPeriodically = function (delayBetweenGestures) {
delayBetweenGestures = delayBetweenGestures !== undefined ? delayBetweenGestures : 50;
var waitThenGo = function waitThenGo() {
periodicGesturesTimeoutID = setTimeout(function () {
window.simulateRandomGesture(waitThenGo);
}, delayBetweenGestures);
};
window.simulateRandomGesture(waitThenGo);
};
window.stopSimulatingGestures = function () {
clearTimeout(gestureTimeoutID);
clearTimeout(periodicGesturesTimeoutID);
};