我正在使用 html5 Canvas + 一些 javascript (onmousedown/move/up) 在网页上创建简单的绘图板。
在 Opera、Firefox、Chrome 等中运行良好(在台式电脑上试用)。但是,如果我使用 iPhone 访问此页面,当我尝试在 Canvas 上绘图时,它会拖动或滚动页面。
这适用于其他页面内容,通过上下滑动页面,您可以像往常一样在移动浏览器中浏览页面。但是有没有一种方法可以在 Canvas 上禁用此行为,以便移动访问者也可以在上面实际绘制一些东西?
为了您的引用,这里有一个简单的例子:
<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>
是否有一些特殊的样式或事件我必须添加到 Canvas ,以避免在 Canvas 中滑动时拖动/滚动页面?
最佳答案
iPad/iPhone 没有鼠标*事件。您需要使用 touchstart
、touchmove
和 touchend
。此事件可以有多个触摸,因此您需要像这样获得第一个:
canvas.ontouchstart = function(e) {
if (e.touches) e = e.touches[0];
return false;
}
在触摸启动方法中返回 false
很重要,否则会触发页面滚动。
关于javascript + html5 Canvas : drawing instead of dragging/scrolling on mobile devices?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9975352/