canvas jquery 移动设备的偏移量

canvas offset for jquery mobile

我在这里支了一支笔

http://codepen.io/prantikv/pen/LEbRKY

我正在使用 canvas 来抚摸鼠标或触摸。当未连接 jquery 或 jquery 移动设备时,它工作正常,但一旦我连接它,我就会在 canvas 中得到一个偏移量,并且绘图仅在 Y 轴上。

我正在使用以下代码绘制:

var el = document.getElementById('c');
var ctx = el.getContext('2d');
var isDrawing;

el.onmousedown = function(e) {
  isDrawing = true;
  ctx.lineWidth = 10;
  ctx.lineJoin = ctx.lineCap = 'round';
  ctx.moveTo(e.clientX, e.clientY);
  console.log(e.clientX, e.clientY);

  console.log(e);
  console.log(e.pageX,e.pageY);
};
el.onmousemove = function(e) {
  if (isDrawing) {
    ctx.lineTo(e.layerX, e.layerY);
    ctx.stroke();
  }
};
el.onmouseup = function() {
  isDrawing = false;
}; 

好像是什么问题。我尝试使用 layerY、pageY 和 screenY,但都不准确。

我应该采用哪些值?

这是解决方案

var el = document.getElementById('c');
var jqEl = jQuery('#c')
var ctx = el.getContext('2d');
var isDrawing;
el.onmousedown = function(e) {
  isDrawing = true;
  ctx.lineWidth = 10;
  ctx.lineJoin = ctx.lineCap = 'round';
  ctx.moveTo(e.clientX - jqEl.position().left, e.clientY - jqEl.position().top);
};
el.onmousemove = function(e) {
  if (isDrawing) {
    ctx.lineTo(e.clientX - jqEl.position().left, e.clientY - jqEl.position().top);
    ctx.stroke();
  }
};
el.onmouseup = function() {
  isDrawing = false;
};