1

我目前正在学习画布触摸事件功能,我想在框内画线,但绘图与鼠标指针不同步。请帮助检查我的代码并指出我犯的错误。谢谢你!

这是编码

<!DOCTYPE html>
<html><head>
<style>
#contain {
width: 500px;
height: 120px;
top : 15px;
margin: 0 auto;
position: relative;    
}
</style>
<script>
      var canvas;
      var ctx;
      var lastPt=null;
      var letsdraw = false;

    function init() {
        var touchzone = document.getElementById("layer1");
        touchzone.addEventListener("touchmove", draw, false);
        touchzone.addEventListener("touchend", end, false);
        ctx = touchzone.getContext("2d");
      }

    function draw(e) {
        e.preventDefault();
        if(lastPt!=null) {
          ctx.beginPath();
          ctx.moveTo(lastPt.x, lastPt.y);
          ctx.lineTo(e.touches[0].pageX, e.touches[0].pageY);
          ctx.stroke();
        }
        lastPt = {x:e.touches[0].pageX, y:e.touches[0].pageY};
      }

    function end(e) {
          var touchzone = document.getElementById("layer1");
        e.preventDefault();
        // Terminate touch path
        lastPt=null;
      }
    function clear_canvas_width ()
        {
            var s = document.getElementById ("layer1");
            var w = s.width;
            s.width = 10;
            s.width = w;
        }
    </script>    
</head>

<body onload="init()">

<div id="contain">
<canvas id="layer1" width="450" height="440" 
   style="position: absolute; left: 0; top: 0;z-index:0; border: 1px solid #ccc;"></canvas> 
</div>

    </body>
</html>
4

1 回答 1

0

正如评论中所建议的,尝试使用偏移量。(演示

如果您有 chrome,请转到开发人员选项卡 -> 设置 -> 覆盖 -> 启用触摸事件以测试上述演示小提琴中的触摸事件。

  var canvas;
  var ctx;
  var lastPt = null;
  var letsdraw = false;
  var offX = 10, offY = 20;


  function init() {
      var touchzone = document.getElementById("layer1");
      touchzone.addEventListener("touchmove", draw, false);
      touchzone.addEventListener("touchend", end, false);
      ctx = touchzone.getContext("2d");
  }

  function draw(e) {
      e.preventDefault();
      if (lastPt != null) {
          ctx.beginPath();
          ctx.moveTo(lastPt.x, lastPt.y);
          ctx.lineTo(e.touches[0].pageX - offX,
                     e.touches[0].pageY - offY);
          ctx.stroke();
      }
      lastPt = {
          x: e.touches[0].pageX - offX,
          y: e.touches[0].pageY - offY
      };
  }

  function end(e) {
      var touchzone = document.getElementById("layer1");
      e.preventDefault();
      // Terminate touch path
      lastPt = null;
  }

  function clear_canvas_width() {
      var s = document.getElementById("layer1");
      var w = s.width;
      s.width = 10;
      s.width = w;
  }
于 2013-10-25T07:38:17.327 回答