在stackoverflow的幫助下,我得到了一個簡單的畫布簽名指令。問題在於它適用於鼠標事件(mousedown,mouseup,mousemove),但不適用於觸摸事件(touchstart,touchmove,touchend)。我在我的主應用程序模塊和保存該指令的模塊中都有ngTouch。我希望你能幫助我。下面的代碼:AngularJS Simple Signature Pad指令(不含jQuery)
var sig = angular.module('signature', ['ngTouch']);
sig.directive("mjav", ['$document', function ($document) {
return {
restrict: "A",
link: function (scope, element) {
var ctx = element[0].getContext('2d');
ctx.canvas.width = window.innerWidth - 20;
var tempCanvas = document.createElement('nanavas');
// variable that decides if something should be drawn on mousemove
var drawing = false;
// the last coordinates before the current move
var lastX;
var lastY;
element.on('touchstart', function (event) {
if (event.offsetX !== undefined) {
lastX = event.offsetX;
lastY = event.offsetY;
} else {
lastX = event.layerX - event.currentTarget.offsetLeft;
lastY = event.layerY - event.currentTarget.offsetTop;
}
// begins new line
ctx.beginPath();
drawing = true;
});
element.on('touchmove', function (event) {
if (drawing) {
// get current mouse position
if (event.offsetX !== undefined) {
currentX = event.offsetX;
currentY = event.offsetY;
} else {
currentX = event.layerX - event.currentTarget.offsetLeft;
currentY = event.layerY - event.currentTarget.offsetTop;
}
draw(lastX, lastY, currentX, currentY);
// set current coordinates to last one
lastX = currentX;
lastY = currentY;
}
});
$document.on('touchend', function (event) {
// stop drawing
drawing = false;
});
// canvas reset
function reset() {
element[0].width = element[0].width;
}
function draw(lX, lY, cX, cY) {
// line from
ctx.moveTo(lX, lY);
// to
ctx.lineTo(cX, cY);
// color
ctx.strokeStyle = "#000";
// draw it
ctx.stroke();
}
}
};
}]);
帆布在移動設備上也很棒,爲什麼你需要觸摸事件? –
這是簡單簽名的必要條件。我需要觸摸事件,所以我可以在畫布上畫畫。上面的代碼適用於鼠標事件(繪圖在桌面上工作),但不適用於觸摸事件。 – Zoneh
好的,我已經確定TOUCH活動能夠發揮作用!麻煩必須與繪圖。但是什麼?當我使用鼠標事件時,一切正常。膠印特性爲touchevents添加了不同的方式嗎? – Zoneh