I am working on developing a sketching application on HTML5 Canvas . I have added ‘Touch Listeners’ to the canvas .
But only touchstart and touchmove events are getting fired. Touchend doesnt get fired. Can anyone explain why and what is the fix ?
<script type="text/javascript" charset="utf-8">
var canvas ;
var context ;
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function(coors){
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function(coors){
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
current_stroke+= coors.x+','+coors.y+';';
context.stroke();
}
},
touchend: function(coors){
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
current_stroke+= coors.x+','+coors.y+';';
context.stroke();
this.isDrawing = false;
}
}
}; // end of drawer
// create a function to pass touch events and coordinates to drawer
function draw(event){
// get the touch coordinates
var coors = {
x: event.targetTouches[0].pageX,
y: event.targetTouches[0].pageY
};
// pass the coordinates to the appropriate handler
drawer[event.type](coors);
}
$(document).ready(function() {
// get the canvas element and its context
canvas = document.getElementById('sketchpad');
context = canvas.getContext('2d');
context.lineWidth = 5;
context.strokeStyle = 'blue';
// attach the touchstart, touchmove, touchend event listeners.
canvas.addEventListener('touchstart',draw, false);
canvas.addEventListener('touchmove',draw, false);
canvas.addEventListener('touchend',draw, false);
// prevent elastic scrolling
document.body.addEventListener('touchmove',function(event){
event.preventDefault();
},false); // end body.onTouchMove
});
</script>
This may be a little late but here goes…
The Touchend event does not register an x and y screen position, because in effect you don’t have your finger on the screen when its fired, and it does not have the ability to recall the last known screen position.
Try using a method such as this…
Within your touchmove function – if you capture the current x and y coords like so: this.lastCoors = {coors.x, coors.y} you will be able to use them in your touchend function in replace of the current coors values
Alternatively it may be wise to re-engineer your code so your Touchend function no longer has a need to use the coors.x and y values all together.