html - 通过鼠标和触摸在 Canvas 上绘图

标签 html canvas touch

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

link

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

最佳答案

这是一个用于绘制鼠标和触摸事件的 HTML 文件。

<!DOCTYPE html>
<html><head><meta charset="utf-8"/><script type='text/javascript'>
window.addEventListener('load', function () {
  // get the canvas element and its context
  var canvas = document.getElementById('sketchpad');
  var context = canvas.getContext('2d');
  var isIdle = true;
  function drawstart(event) {
    context.beginPath();
    context.moveTo(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop);
    isIdle = false;
  }
  function drawmove(event) {
    if (isIdle) return;
    context.lineTo(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop);
    context.stroke();
  }
  function drawend(event) {
    if (isIdle) return;
    drawmove(event);
    isIdle = true;
  }
  function touchstart(event) { drawstart(event.touches[0]) }
  function touchmove(event) { drawmove(event.touches[0]); event.preventDefault(); }
  function touchend(event) { drawend(event.changedTouches[0]) }

  canvas.addEventListener('touchstart', touchstart, false);
  canvas.addEventListener('touchmove', touchmove, false);
  canvas.addEventListener('touchend', touchend, false);        

  canvas.addEventListener('mousedown', drawstart, false);
  canvas.addEventListener('mousemove', drawmove, false);
  canvas.addEventListener('mouseup', drawend, false);

}, false); // end window.onLoad
</script></head><body  encoding='utf8'>
  <canvas id='sketchpad' width='500' height='500' style='border:1px solid #777'/>
</body></html>

关于html - 通过鼠标和触摸在 Canvas 上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16057256/

相关文章:

jquery - 我怎样才能同时制作2个div的滚动条

JavaFX Canvas 双缓冲

javascript - EaselJS:更新属性更改时的形状颜色

touch - jquery - 如果原始目标是链接/图像,则 touchend PreventDefault

javascript - Android 上的 Chrome 中如何防止长按焦点发生变化?

html - 旋转和对齐 div

javascript - 在动态生成的 HTML 中使用 CSS 布局标签/输入/选择元素的问题

java - jsoup : How to search for date text from a webpage

javascript - 如何更改 ChartJS 3 中饼图段悬停上的光标?

ios - UITableView 的 backgroundView 上的触摸事件