本文介绍了通过鼠标和触摸在画布上绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to draw on a canvas, works great with a mouse, but how do I have to modify the code to make it run on iPad or Nexus as well?

链接

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

推荐答案

您需要使用的事件是 touchstarttouchendtouchmove>,应与上述功能相对应.我不知道在普通 JS 中是否可以像在 jQuery 中一样轻松地堆叠事件,但是通过将每个事件转换为函数,您应该能够同时支持鼠标和触摸:

The events you need to use are touchstart, touchend, and touchmove, which should correspond with the functions above. I don't know if events can be stacked as easily in plain JS as in jQuery, but you should be able to support both mouse and touch either by turning each event into functions:

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

这篇关于通过鼠标和触摸在画布上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 23:29
查看更多