0

I have a Html 5 Canvas what takes up 100% of the width and 90% of the height (the top 90%) of the screen. Im trying to make an eraser that as a user touches and drags it makes anything on the canvas transparent. The problem is the "eraser" is about 20-30px lower than the users finger when they touch. Ive experimented around but it isn't changing. Any ideas?

var canvas=document.getElementById("viewport"); // grabs the canvas element
var context=canvas.getContext("2d"); // returns the 2d context object

canvas.addEventListener("touchmove", function (e) {
    e.preventDefault();
    drawPoint(e.touches[0].screenX - canvas.offsetLeft, e.touches[0].screenY - canvas.offsetTop);
}, false);


function drawPoint(x, y) {
   var canvas=document.getElementById("viewport"); // grabs the canvas element
   var context=canvas.getContext("2d"); // returns the 2d context object
   context.fillStyle = "rgba(0,0,0,1)"; // (Drawing with 0 alpha pretty much means doing nothing)
   context.globalCompositeOperation = "destination-out";
   context.beginPath();
   context.arc(x, y, 10, 0, Math.PI * 2, true);
   context.fill();
   context.closePath();
}
Gilko
  • 2,280
  • 8
  • 36
  • 45
DasBeasto
  • 2,082
  • 5
  • 25
  • 65
  • 1
    Is your canvas inside of anything else? I remember having a similar issue and I needed to used a more elaborate offset function as opposed to just the basic `offsetLeft` property. If you can use jQuery I would recommend simply using `.offset()`. – EvilZebra Jan 06 '15 at 00:53
  • 1
    Also `screenX/Y` are relative to the screen while `offsetLeft/Top` are relative to the `offsetParent`. – Robert Jan 06 '15 at 00:55
  • The canvas is in side a div that takes up the whole 100% by 100%, so the canvas is just 10% shorter height. But i figured since x/y start at the top right that shouldnt make a difference right? I also tried the different varients of screenX/Y but they seemed to make it worse (i.e. not 20px off but just all the way off) – DasBeasto Jan 06 '15 at 02:17
  • You might want to adapt my answer to touch : http://stackoverflow.com/a/20061533/856501 – GameAlchemist Jan 07 '15 at 09:06

0 Answers0