我基本上是用它来使图像在画布中可拖动。 Make image drawn on canvas draggable with JavaScript
我正在尝试添加触摸事件,除touchleave之外的所有触摸事件都可以工作。当用户尝试将图像拖到画布之外时,touchleave事件似乎没有触发。是否有其他适用于此目的的触摸事件?
最佳答案
请参阅this。它们实际上是在触发触摸事件的鼠标事件。这可能对您有帮助。
touchstart – to toggle drawing mode “on”
touchend – to toggle drawing mode “off”
touchmove – to track finger position, used in drawing
// Set up touch events for mobile, etc
canvas.addEventListener("touchstart", function (e) {
mousePos = getTouchPos(canvas, e);
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousedown", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}, false);
canvas.addEventListener("touchend", function (e) {
var mouseEvent = new MouseEvent("mouseup", {});
canvas.dispatchEvent(mouseEvent);
}, false);
canvas.addEventListener("touchmove", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousemove", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}, false);
// Get the position of a touch relative to the canvas
function getTouchPos(canvasDom, touchEvent) {
var rect = canvasDom.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - rect.left,
y: touchEvent.touches[0].clientY - rect.top
};
}
关于javascript - 离开 Canvas jQuery时touchleave不触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43692542/