Draw a square on HTML5 canvas with touch events

I have a problem, I am trying to draw a square on the canvas using a touch event, and it is not working, can someone help me understand why?


Here is my 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); } init(); } 

HTML5:

  <div id="canvasDiv"> <canvas id="canvasSignature" width="580px" height="788px" style="border:2px solid #000; background: #FFF;"></canvas> </div> <div id="rect"> <p><button onclick="rect();">Rectangle</button></p> </div> 

Thanks again, Wardenclyffe

+4
source share
1 answer

Tested in Chrome with emulated touch events working with this jsFiddle The problem is how you are binding the click event. I just used jQuery.

Or without jQuery: just a simple addEventListener

+1
source

Source: https://habr.com/ru/post/1416451/


All Articles