0

我正在尝试在 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>

我不明白我错过了什么。有没有人可以帮助我.....我将不胜感激!

4

1 回答 1

0

您正在从错误的数组中获取触摸结束坐标。

事件对象还有一个称为数组的数组changedTouches,您可以在其中找到触摸结束点的坐标。这些结束坐标不在targetTouches数组中。所以你需要

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

[修改上面的代码以适应您的场景。希望你明白这个概念......而且我过去也被困在同一点上,浪费了一个多小时才知道这个事实......]

于 2013-07-02T16:48:36.153 回答