如何在canvas HTML5中使用ontouch事件?

时间:2013-10-04 10:25:36

标签: javascript cordova html5-canvas

我是这个网站的新手,这是我在这里问的第一个问题..如果它简单请原谅我.. 我已经绘制了一个背景图像,在此我使用drawImage()方法绘制了5个小的小图像。一旦我触摸小图像然后它们应该消失或者应该弹出一个警告框但是触摸事件没有发生到目前为止我已经搜索了ontouch事件但没有用。我不想通过HTML中的img标签绘制图像。 这是我的代码段

var car = new Image();
car.src = "img/car.jpg";
    car.onload = function() {
    imgLoaded = true;
}
if (imgLoaded = true) {
    drawBackgroundImg();
    drawCarImg();

}


 function drawCarImg() {
if (i == 0) {
    x1 = Math.floor((Math.random() * 501));
    y1 = Math.floor((Math.random() * 301));
    cxt.save();
    cxt.drawImage(car, x1, y1, car.width, car.height);
    cxt.restore();

   }
  }
 car.on('touchstart', function() {
 alert("T");
 });

Here is my HTML code

<!DOCTYPE html>
  <body>   
<div id="container" onclick="void(0)">
    <canvas id="can"> </canvas>

</div>
<div id="btn">
    <input type="image" id="zoomIn" src="img/up.png" onclick="zoomIn()" />
    <input type="image" id="zoomOut" src="img/down.png"
        onclick="zoomOut()" />
</div>
<div id="score">
    <p id="scoreCount">
        <b></b>
    </p>
</div>
 </body>
</html>

有人可以帮我解决问题。 仅供参考:我在Phonegap中运行此代码而不是在浏览器中运行。

3 个答案:

答案 0 :(得分:0)

$( '#id' ).on( 'touchstart',function(){
                     //your code
                       });

此处id是您要在其上侦听触摸事件的html元素的ID。

答案 1 :(得分:0)

$('#id').on('touchmove',function(){
      alert("T");

  }); 
$('#id').on('click',function(){
       alert("T");

});

答案 2 :(得分:0)

我找到了答案,我将div设为隐形,并将图像放置在绝对位置并使用图像的id并触发touchstart事件。 上面这个例子

  $('#id').on('touchmove',function(){
  alert("T");

   }); 
 $('#id').on('click',function(){
   alert("T");

  });