2013-10-25 67 views
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> 
+1

您需要检查元件偏移 – orhanhenrik

+0

您遇到的错误是什么?请考虑使用http://codereview.stackexchange.com – loxxy

回答

0

正如意见建议尝试使用的偏移量。 (DEMO

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

但是,当我使用谷歌浏览器打开HTML文件,画布鼠标指针仍然没有同步?我可以知道为什么吗?我只能在鼠标指向左侧时画线。 – user2913749

+0

你看过演示了吗? – loxxy

+0

是的。我将代码保存为HTML文件,并使用chrome打开,但显示为全屏大小。鼠标指针仍未同步。谢谢 – user2913749