2013-07-02 76 views
0

我想在iPad上使用畫布對象;用戶需要用手指畫一條自由曲線,當他釋放手指時,系統必須關閉曲線並填充它。帆布closePath手指在iPad上發佈

其實我寫下了下面的代碼,但問題是它繪製,但它並沒有關閉手指釋放的路徑。

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
<meta charset="utf-8"> 
<meta name="viewport" content="width=768px, maximum-scale=1.0" /> 
<title>sketchpad</title>  
<script type="text/javascript" charset="utf-8"> 
window.addEventListener('load',function(){ 
    // get the canvas element and its context 
    var canvas = document.getElementById('sketchpad'); 
    var context = canvas.getContext('2d'); 
    var img = new Image(); 
    img.src = 'imp_02.jpg'; 
    context.drawImage(img,0,0,600,600); 
    var colorPurple = "#cb3594"; 
    context.strokeStyle=colorPurple; 
    context.lineWidth = 5; 
    context.fillStyle = "red"; 

    // create a drawer which tracks touch movements 
    var drawer = { 
     isDrawing: false, 
     touchstart: function(coors){ 
      context.beginPath(); 
      context.moveTo(coors.x, coors.y); 
      this.isDrawing = true; 
     }, 
     touchmove: function(coors){ 
      if (this.isDrawing) { 
       context.lineTo(coors.x, coors.y); 
       context.stroke(); 
      } 
     }, 
     touchend: function(coors){ 
      if (this.isDrawing) { 
       context.touchmove(coors); 
       context.closePath(); 
       this.isDrawing = false; 
      } 
     } 
    }; 
    // create a function to pass touch events and coordinates to drawer 
    function draw(event){ 
     // get the touch coordinates 
     var coors = { 
      x: event.targetTouches[0].pageX, 
      y: event.targetTouches[0].pageY 
     }; 
     // pass the coordinates to the appropriate handler 
     drawer[event.type](coors); 
    } 

    // attach the touchstart, touchmove, touchend event listeners. 
    canvas.addEventListener('touchstart',draw, false); 
    canvas.addEventListener('touchmove',draw, false); 
    canvas.addEventListener('touchend',draw, false); 

    // prevent elastic scrolling 
    document.body.addEventListener('touchmove',function(event){ 
     event.preventDefault(); 
    },false); // end body.onTouchMove 

},false); // end window.onLoad 
</script> 
<style type="text/css"><!-- 
    body{margin:0;padding:0; font-family:Arial;} 
    #container{position:relative;} 
    #sketchpad{ border: 1px solid #000;}   
--></style> 
</head> 
<body> 
<div id="container"> 
    <canvas id="sketchpad" width="766" height="944"> 
     Sorry, your browser is not supported. 
    </canvas>  
</div> 
</body> 
</html> 

我不明白我錯過了什麼。 有沒有人可以幫助我.....我會很感激!

回答

0

您正在從錯誤的數組中提取觸摸端座標。

事件對象還有一個名爲changedTouches的數組,您可以在其中找到觸摸結束點的座標。這些結束座標不在targetTouches數組中。 所以你需要

endCoordX = event.changedTouches[0].pageX; 
endCoordY = event.changedTouches[0].pageY; 

[修改上面的代碼以適應您的方案。希望你有這個概念....而且,我也很重視過去同樣的觀點,浪費了一個多小時才知道這個事實....]