如何设置触摸事件的偏移量

时间:2013-07-12 16:09:30

标签: html5 canvas offset touch-event

我没有得到ipad中x和y坐标的确切位置。有人可以解释我做错了什么吗?这是一个儿童绘画应用程序,他们可以使用画布在图像上着色。它的颜色,但错误是它在用户触摸屏幕的点开始,略低于接触点。您可以在手机或平板电脑上进行测试..其链接为http://talentedash.co.uk/color/paint.html。不要在桌面上尝试这个,因为它不会工作

<script type="text/javascript">
  var canvas = null; //canvas object
  var context = null; //canvas's context object
  var clearBtn = null; //clear button object
  var defaultColor="#3577BB";
  var defaultShape="round";
  var defaultWidth=50;

  /*boolean var to check if the touchstart event
  is caused and then record the initial co-ordinate*/
  var buttonDown = false;

  //onLoad event register
  window.addEventListener('load', initApp, false);

  function initApp() {
    setTimeout(function() { window.scrollTo(0, 1); }, 10); //hide the address bar of the browser.
    canvas = document.getElementById('paintBox');
    clearBtn = document.getElementById('clearBtn');

    initializeEvents();

    context = canvas.getContext('2d'); //get the 2D drawing context of the canvas
    context.strokeStyle = defaultColor;
    context.lineJoin = defaultShape;
    context.lineWidth = defaultWidth;

  /*Main image*/
      function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        // get num of sources
        for(var src in sources) {
          numImages++;
        }
        for(var src in sources) {
          images[src] = new Image();
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images);
            }
          };
          images[src].src = sources[src];
        }
      }

      var sources = {
        main: 'transparent-charac1.png',
      };

      loadImages(sources, function(images) {
        context.drawImage(images.main, 0, 0, 400, 800);
        context.globalCompositeOperation = "destination-atop";
      });
}


function initializeEvents() {
  canvas.addEventListener('touchstart', startPaint, false);
  canvas.addEventListener('touchmove', continuePaint, false);
  canvas.addEventListener('touchend', stopPaint, false);

  clearBtn.addEventListener('touchend', clearCanvas,false);
}


function clearCanvas() {
  context.clearRect(0,0,canvas.width,canvas.height);
}

function startPaint(evt) {
  if(!buttonDown)
  {
    context.beginPath();
    context.moveTo(evt.touches[0].pageX, evt.touches[0].pageY);
    buttonDown = true;
  }
  evt.preventDefault();
}

function continuePaint(evt) {
  if(buttonDown)
  {
    context.lineTo(evt.touches[0].pageX ,evt.touches[0].pageY);
    context.stroke();
  }
}
function setColor(col)
{
    context.strokeStyle = col;
}

function setSize(px)
{
    context.lineWidth=px;
}
function stopPaint() {
  buttonDown = false;
}
</script>

0 个答案:

没有答案