画布鼠标指针未同步

canvas mouse pointer not synced

本文关键字:同步 鼠标指针      更新时间:2023-09-26

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

这是编码

<!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>

如注释中的建议,请尝试使用偏移量。(演示)

如果您有 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;
  }