touch+mouse lib

by Maks M.

HTML

<canvas height='320' width='480' id='canvas'></canvas>

CSS

#canvas {
  border: 1px solid #000;
}

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

this.pointer = {
  x: 0,
  y: 0,
  startX: 0, //точка нажатия для перетаскивания
  startY: 0,
  isMobile: ("ontouchstart" in window),
  isDown: false,
  onDown: function(e) {
    var pointer = this.sensor ? e.targetTouches[0] : e;
    this.startX = pointer.clientX - canvas.offsetLeft;
    this.startY = pointer.clientY - canvas.offsetTop;
    this.x = this.startX;
    this.y = this.startY;
    this.isDown = true;
    if (this.down) this.down(e);
  },
  onMove: function(e) {
    var pointer = this.sensor ? e.targetTouches[0] : e;
    this.x = pointer.clientX - canvas.offsetLeft;
    this.y = pointer.clientY - canvas.offsetTop;
    if (this.move) this.move(e);
  },
  onUp: function(e) {
    this.isDown = false;
    if (this.up) this.up(e);
  }
}

if (!this.pointer.sensor) { //мышь
  window.onmousedown = function(e) {
    self.pointer.onDown(e);
  }
  window.onmousemove = function(e) {
    self.pointer.onMove(e);
  }
  window.onmouseup = function(e) {
    self.pointer.onUp(e);
  }
} else { //or e.changedTouches;
  window.ontouchstart = function(e) {
    self.pointer.onDown(e);
    e.preventDefault();
  }
  window.ontouchmove = function(e) {
    self.pointer.onMove(e);
    e.preventDefault();
  }
  window.ontouchend = function(e) {
    self.pointer.onUp(e);
    e.preventDefault();
  }
  window.ontouchcancel = function(e) {
    self.pointer.onUp(e);
    e.preventDefault();
  }
  window.oncontextmenu = function(e) {
    e.preventDefault();
  }
}

//Функции для использования

this.pointer.down = function() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillText("mouse/touch down", 20, 20);
}

this.pointer.move = function() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillText("mouse/touch move", 20, 20);
}

this.pointer.up = function() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillText("mouse/touch up", 20, 20);
}