我试着用手指在画布元素中写字。它可以在桌面浏览器上运行,但不能在ipad上运行。
我也试过使用touchstart、touchend和touchsmove事件,但在ipad上不起作用。
var pizarra_canvas
var pizarra_context
function init(){
pizarra_canvas = document.getElementById("pizarra");
pizarra_context = pizarra_canvas.getContext("2d");
pizarra_context.strokeStyle = "#000";
pizarra_canvas.addEventListener('mousedown',empezarPintar,false);
pizarra_canvas.addEventListener('mouseup',terminarPintar,false);
}
function empezarPintar(e){
pizarra_context.beginPath();
pizarra_context.moveTo(e.clientX-pizarra_canvas.offsetLeft,e.clientY-pizarra_canvas.offsetTop);
pizarra_canvas.addEventListener('mousemove',pintar,false)
}
function terminarPintar(e){
pizarra_canvas.removeEventListener('mousemove',pintar,false);
}
function pintar(e) {
pizarra_context.lineTo(e.clientX-pizarra_canvas.offsetLeft,e.clientY-pizarra_canvas.offsetTop);
pizarra_context.stroke();
}
最佳答案
您需要取消默认事件(滚动)。此外,最好在文档上触发mouseup/touchend,因为如果离开拖动区域并释放按钮,则画布不知道它应该停止绘制。
var pizarra_canvas
var pizarra_context
function init(){
pizarra_canvas = document.getElementById("pizarra");
pizarra_context = pizarra_canvas.getContext("2d");
pizarra_context.strokeStyle = "#000";
pizarra_canvas.addEventListener('mousedown',empezarPintar,false);
pizarra_canvas.addEventListener('touchstart',empezarPintar,false);
document.addEventListener('mouseup',terminarPintar,false);
document.addEventListener('touchend',terminarPintar,false);
}
function empezarPintar(e){
e.preventDefault();
pizarra_context.beginPath();
pizarra_context.moveTo(e.pageX-pizarra_canvas.offsetLeft,e.pageY-pizarra_canvas.offsetTop);
pizarra_canvas.addEventListener('mousemove',pintar,false)
pizarra_canvas.addEventListener('touchmove',pintar,false)
}
function terminarPintar(e){
e.preventDefault();
pizarra_canvas.removeEventListener('mousemove',pintar,false);
pizarra_canvas.addEventListener('touchmove',pintar,false)
}
function pintar(e) {
e.preventDefault();
pizarra_context.lineTo(e.clientX-pizarra_canvas.offsetLeft,e.clientY-pizarra_canvas.offsetTop);
pizarra_context.stroke();
}
init();
此外,您的css应该在触摸设备上具有类似的功能:
body, html {
height: 100%;
overflow: hidden;
}