简体   繁体   English

触摸在HTML5画布上绘制正方形

[英]Touch Draw A Square On An HTML5 Canvas

First off, the square draws fine and it does work, but there are still a couple of issues. 首先,正方形绘制得很好并且可以工作,但是仍然存在一些问题。 I have two problems... the first one is that when I draw the square, it's unable to collapse back on itself to a single point (and get smaller) if you made your square too big. 我有两个问题……第一个问题是,当我绘制正方形时,如果将正方形过大,它将无法自身折回到单个点(并变小)。 The second problems is that when I draw the square, it shows up about a centimeter below my finger, rather than directly underneath it. 第二个问题是,当我绘制正方形时,正方形显示在手指下方约一厘米处,而不是直接在其下方。

Can anyone help me out with these problems? 谁能帮我解决这些问题?


Here's the code: 这是代码:

JAVASCRIPT JAVASCRIPT

// "Draw Rectangle" Button
function rect(){
var canvas = document.getElementById('canvasSignature'), ctx = canvas.getContext('2d'), rect = {}, drag = false;

function init() {
  canvas.addEventListener("touchstart", touchHandler, false);
  canvas.addEventListener("touchmove", touchHandler, false);
  canvas.addEventListener("touchend", touchHandler, false);
}


function touchHandler(event) {
  if (event.targetTouches.length == 1) { //one finger touche
    var touch = event.targetTouches[0];

    if (event.type == "touchstart") {
      rect.startX = touch.pageX;
      rect.startY = touch.pageY;
      drag = true;
    } else if (event.type == "touchmove") {
      if (drag) {
        rect.w = touch.pageX - rect.startX;
        rect.h = touch.pageY - rect.startY ;
        draw();
      }
    } else if (event.type == "touchend" || event.type == "touchcancel") {
      drag = false;
    }
  }
}

function draw() {
  ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
  ctx.fillStyle = "orange";
}

init();
}

Thanks, Wardenclyffe 谢谢,Wardenclyffe

The first problem is caused by you not clearing the canvas. 第一个问题是由于您没有清除画布引起的。 The previous data will remain in the canvas unless you clear it, and so the previously-drawn rectangle will remain. 除非您清除它,否则先前的数据将保留在画布中,因此,先前绘制的矩形将保留。 You can clear the canvas like this: 您可以像这样清除画布:

ctx.clearRect(0, 0, canvas.width, canvas.height);

I assume your second problem is that you're using the page-relative X and Y and expecting it to be the canvas-relative X and Y. This is not the case unless the canvas's upper left hand corner is the same as the document's upper left hand corner. 我认为您的第二个问题是您使用的是相对于页面的X和Y,并且期望它是相对于画布的X和Y。除非画布的左上角与文档的上角相同,否则情况并非如此。左上角。 You can transform a page X and Y into a canvas X and Y in newer browsers like this: 您可以在较新的浏览器中将页面X和Y转换为画布X和Y,如下所示:

var clientRect = canvas.getBoundingClientRect();
var canvasX = touch.pageX - clientRect.left - window.pageXOffset,
    canvasY = touch.pageY - clientRect.top  - window.pageYOffset;

This will need further tweaking if the canvas is in an element with a scrollbar. 如果画布位于带有滚动条的元素中,则需要进一步调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM