获取画布 X 和 Y 坐标并显示在屏幕上

Get Canvas X and Y coordinates and show on screen

本文关键字:显示 屏幕 坐标 获取      更新时间:2023-09-26

我目前正在学习画布触摸事件功能,我可以在画布上画线,现在我想在绘制任何线条并显示在屏幕上时获取x和y坐标

这是编码

<!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;
      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;
        }
    </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>

仍然不完全有信心,我理解你的问题。

在您发布的代码中,您已经使用 e.touches[0].pageX/Y 获取坐标。 这样做的主要问题是 pageX/Y 值是相对于页面原点的。 然后,在代码中减去固定的 offX/Y,以尝试将这些坐标转换为画布相对坐标。 正确的想法,错误的价值观。 您需要减去画布元素的位置,该位置可以通过在使用 offsetParent 引用向上遍历树时对 offsetX/Y 值求和来获得。

像这样:

offX=0;offY=0;
node = document.getElementById ("layer1");
do {
    offX += node.offsetX;
    offY += node.offsetY;
    node = node.offsetParent;
} while(node);

应该会给你一个更好的 offX 和 offY 值。

如果您只想在最后找到实际绘图,最简单的方法是在用户绘制时跟踪边界框。