2012-04-02 32 views
6

我使用html5画布+一些JavaScript(onmousedown/move/up)在网页上创建简单的绘图板。javascript + html5 canvas:绘图而不是在移动设备上拖动/滚动?

适用于Opera,Firefox,Chrome等(在台式电脑上试用)。但是如果我用iPhone访问这个页面,当试图在画布上绘画时,它会拖动或滚动页面。

这对其他页面内容很好,通过向下滑动页面,您可以照常在移动浏览器中浏览页面。但是,是否有办法在画布上禁用此行为,以便移动访问者也可以在其上绘制某些内容?

供您参考,这里有一个minimalisic例如:

<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> 

有一些特殊的风格或事件我要补充到画布上,以避免拖动/在画布上刷卡时,滚动网页?

回答

6

iPad/iPhone没有鼠标*事件。您需要使用touchstart,touchmovetouchend

canvas.ontouchstart = function(e) { 
    if (e.touches) e = e.touches[0]; 
    return false; 
} 

它在触摸启动方法return false重要的,因为否则页面滚动触发:所以你需要得到第一个这样的事件,这可以有多个触摸。

+0

啊,说得通。之前从未注意到这些。谢谢! – 2012-04-02 14:12:31

+0

在Android上这不起作用,但你可以按照规范使用'e.preventDefault();'http://www.w3.org/TR/touch-events/#the-touchstart------ - -事件 – lapo 2012-08-29 10:11:22