Wardenclyffe
Wardenclyffe

Reputation: 2551

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

// "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

Upvotes: 1

Views: 958

Answers (1)

icktoofay
icktoofay

Reputation: 129139

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. You can transform a page X and Y into a canvas X and Y in newer browsers like this:

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.

Upvotes: 1

Related Questions