[英]Draw a Square on the HTML5 Canvas With Touch Events
I have a problem, I'm trying to draw a square on the canvas with the use of touch event and it not working, can someone help me figure out why? 我有一个问题,我试图在画布上使用触摸事件绘制一个正方形并且它不起作用,有人可以帮我找出原因吗?
Here's my code so far: 到目前为止,这是我的代码:
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);
}
init();
}
HTML5: 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 再次感谢Wardenclyffe
Tested in Chrome with emulated touch events works with this jsFiddle The problem seems to be the way you bind your click event. 使用模拟触摸事件在Chrome中进行测试可以使用此jsFiddle问题似乎是绑定点击事件的方式。 I just used jQuery. 我刚刚使用了jQuery。
Or without jQuery: just a plain addEventListener 或者没有jQuery: 只是一个简单的addEventListener
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.