Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw on a Canvas via mouse and touch

Tags:

html

canvas

touch

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);
like image 453
daisy Avatar asked Apr 17 '13 10:04

daisy


1 Answers

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);
like image 146
David Millar Avatar answered Oct 18 '22 19:10

David Millar