通过鼠标和触摸在画布上绘图

时间:2013-04-17 10:06:39

标签: html5 canvas touch

我想在画布上绘图,使用鼠标效果很好,但我如何修改代码以使其在iPad或Nexus上运行?

[链接] http://jsfiddle.net/FgNQk/6/

 var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var width  = window.innerWidth;
    var height = window.innerHeight;
    canvas.height = height;
    canvas.width = width;

    canvas.addEventListener('mousedown', function(e) {
        this.down = true;   
        this.X = e.pageX ;
        this.Y = e.pageY ;
    }, 0);

    canvas.addEventListener('mouseup', function() {
        this.down = false;          
    }, 0);

    canvas.addEventListener('mousemove', function(e) {

        if(this.down) {
             with(ctx) {
                beginPath();
                moveTo(this.X, this.Y);
                lineTo(e.pageX , e.pageY );
                ctx.lineWidth=1;
                stroke();
             }
             this.X = e.pageX ;
             this.Y = e.pageY ;
        }
    }, 0);

2 个答案:

答案 0 :(得分:1)

您需要使用的事件包括touchstarttouchendtouchmove,它们应与上述功能相对应。我不知道事件是否可以像普通JS一样容易地堆叠在jQuery中,但是你应该能够通过将每个事件转换为函数来支持鼠标和触摸:

var myMoveEvent = function (e) {
    if(this.down) {
         with(ctx) {
            beginPath();
            moveTo(this.X, this.Y);
            lineTo(e.pageX , e.pageY );
            ctx.lineWidth=1;
            stroke();
         }
         this.X = e.pageX ;
         this.Y = e.pageY ;
    }
}

canvas
    .addEventListener('mousemove', function(e) {
        myMoveEvent(e);
    }, 0)
    .addEventListener('touchmove', function(e) {
        myMoveEvent(e);
    }, 0);

答案 1 :(得分:0)

使用事件touchstarttouchendtouchmove,但更为复杂,因为坐标不在pageX和pageY中,而是所有手指的坐标都在数组中:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width  = window.innerWidth;
var height = window.innerHeight;
canvas.height = height;
canvas.width = width;

canvas.addEventListener('touchstart', function(e) {
  this.down = true;   
  this.X = e.touches[0].pageX ;
  this.Y = e.touches[0].pageY ;
}, 0);

canvas.addEventListener('touchend', function() {
  this.down = false;          
}, 0);

canvas.addEventListener('touchmove', function(e) {
  if(this.down) {
    with(ctx) {
      beginPath();
      moveTo(this.X, this.Y);
      lineTo(e.touches[0].pageX , e.touches[0].pageY );
      ctx.lineWidth=1;
      stroke();
    }
    this.X = e.touches[0].pageX ;
    this.Y = e.touches[0].pageY ;
  }
}, 0);

但这不能解决常见的问题,以使其与鼠标和触摸兼容。如果您感兴趣,我搜索了解决方案并找到了该解决方案:http://bencentra.com/code/2014/12/05/html5-canvas-touch-events.html 同样,如果任务将更加复杂,则必须找到默认智能手机浏览器行为的解决方案,该行为在触发touchstart浏览器时也会触发其他事件mousedown + mouseup + click(这是为了与非触摸式网站)。使用Event.preventDefault()可以暂时针对实际的触摸事件禁用此行为。