我正试图让一个标志垫起作用。
我设法使用鼠标工作没有问题,我在这里找到一段代码:http://demos.ijasoneverett.com/html5-sigpad.php
然而,它似乎不适用于移动设备,我不明白为什么,因为我已经添加了事件监听器
canvas.addEventListener("touchstart", mouseDown, false);
canvas.addEventListener("touchmove", mouseXY, true);
canvas.addEventListener("touchend", mouseUp, false);
这是我所有的jQuery:
$(document).ready(function () {
//User Variables
var canvas = document.getElementById('canvas'); //canvas element
var context = canvas.getContext("2d"); //context element
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mousemove", mouseXY, false);
document.body.addEventListener("mouseup", mouseUp, false);
//For mobile
canvas.addEventListener("touchstart", mouseDown, false);
canvas.addEventListener("touchmove", mouseXY, true);
canvas.addEventListener("touchend", mouseUp, false);
document.body.addEventListener("touchcancel", mouseUp, false);
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height); // Clears the canvas
context.strokeStyle = "#000000"; //set the "ink" color
context.lineJoin = "miter"; //line join
context.lineWidth = 2; //"ink" width
for (var i = 0; i < clickX.length; i++) {
context.beginPath(); //create a path
if (clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]); //move to
} else {
context.moveTo(clickX[i] - 1, clickY[i]); //move to
}
context.lineTo(clickX[i], clickY[i]); //draw a line
context.stroke(); //filled with "ink"
context.closePath(); //close path
}
}
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function mouseXY(e) {
if (paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop - 40, true);
draw();
}
}
function mouseUp() {
paint = false;
}
function mouseDown(e)
{
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop - 40);
draw();
}
//Clear the Zig
document.getElementById("clearSig").onclick = function () {
clickX = new Array();
clickY = new Array();
clickDrag = new Array();
context.clearRect(0, 0, canvas.width, canvas.height);
$("#imgData").html('');
};
});
答案 0 :(得分:1)
要获得pageX
和pageY
的正确值,您必须为移动设备使用e.touches
(e.changedTouches)。例如:
function mouseXY (e) {
var touches = e.touches || [];
var touch = touches[0] || {};
if (paint) {
addClick(touch.pageX - this.offsetLeft, touch.pageY - this.offsetTop - 40, true);
draw();
}
}
在https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
上查看更多相关信息