I want to draw on a canvas, works great with a mouse, but how do I have to modify the code to make it run on iPad or Nexus as well?
link
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = window.innerWidth;
var height = window.innerHeight;
canvas.height = height;
canvas.width = width;
canvas.addEventListener('mousedown', function(e) {
this.down = true;
this.X = e.pageX ;
this.Y = e.pageY ;
}, 0);
canvas.addEventListener('mouseup', function() {
this.down = false;
}, 0);
canvas.addEventListener('mousemove', function(e) {
if(this.down) {
with(ctx) {
beginPath();
moveTo(this.X, this.Y);
lineTo(e.pageX , e.pageY );
ctx.lineWidth=1;
stroke();
}
this.X = e.pageX ;
this.Y = e.pageY ;
}
}, 0);
The events you need to use are touchstart
, touchend
, and touchmove
, which should correspond with the functions above. I don't know if events can be stacked as easily in plain JS as in jQuery, but you should be able to support both mouse and touch either by turning each event into functions:
var myMoveEvent = function (e) {
if(this.down) {
with(ctx) {
beginPath();
moveTo(this.X, this.Y);
lineTo(e.pageX , e.pageY );
ctx.lineWidth=1;
stroke();
}
this.X = e.pageX ;
this.Y = e.pageY ;
}
}
canvas
.addEventListener('mousemove', function(e) {
myMoveEvent(e);
}, 0)
.addEventListener('touchmove', function(e) {
myMoveEvent(e);
}, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With