简体   繁体   中英

How to use ontouch event in canvas HTML5?

I am new to this site and this is first question I am asking here..if its simple pls forgive me.. I have drawn one background image, on this I am drawing 5 small small images by using drawImage() method. Once I touch the small images then they should disappear or should pop up one alert box but ontouch event is not occurring so far I have searched for ontouch event but no use. I dont want to draw images through img tag in HTML. Here is my code segment

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>

Could anybody help me to get the solution. FYI: I am running this code in Phonegap NOT in browser.

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

here id is id of your html element on which you want to listen touch event.

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

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

});

I have found the answer, I made div with invisible and placed the images with position absolute and use the id's of images and trigger the touchstart event. above said example here

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

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

  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM