She*_*man 7 javascript mobile draw drag html5-canvas
我正在使用html5画布+一些javascript(onmousedown/move/up)在网页上创建简单的绘图板.
在Opera,Firefox,Chrome等中运行正常(在台式机上试用).但是如果我用iPhone访问这个页面,当试图在画布上绘图时,它会拖动或滚动页面.
这适用于其他页面内容,通过向下滑动页面,您可以像往常一样在移动浏览器中浏览页面.但有没有办法在画布上禁用此行为,以便移动访问者可以实际上在其上绘制一些东西?
供您参考,这是一个简洁的例子:
<html><head><script type='text/javascript'>
function init()
{
  var canvas = document.getElementById('MyCanvas');
  var ctx = canvas.getContext('2d');
  var x = null;
  var y;
  canvas.onmousedown = function(e)
  {
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetTop;
    ctx.beginPath();
    ctx.moveTo(x,y);
  }
  canvas.onmouseup = function(e)
  {
    x = null;
  }  
  canvas.onmousemove = function(e)
  {
    if (x==null) return;
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetLeft;
    ctx.lineTo(x,y);
    ctx.stroke();
  }  
}
</script></head><body onload='init()'>
<canvas id='MyCanvas' width='500' height='500' style='border:1px solid #777'>
</canvas></body></html>
是否有一些特殊的样式或事件我必须添加到画布中,以避免在画布中滑动时拖动/滚动页面?
iPad/iPhone没有鼠标*事件.你需要使用touchstart,touchmove和touchend.这个事件可以有多个触摸,所以你需要得到这样的第一个:
canvas.ontouchstart = function(e) {
  if (e.touches) e = e.touches[0];
  return false;
}
return false触摸启动方法很重要,否则会触发页面滚动.