cordova(phonegap):在画布中拖动图片在浏览器中工作正常但在移动设备中没有

时间:2014-08-22 06:16:36

标签: javascript html5 cordova canvas

我正在创建一个应用程序,我需要图片内的画布,当我在画布内移动图像时,它应该返回图像位置的坐标。在谷歌长搜索后我得到了一个必需的代码。但它在浏览器中工作正常。当我为移动设备构建它不起作用。有人告诉我,我怎样才能使它与移动设备兼容。我发布了我的代码,下面是在Browser.Thanks提前工作

 <div id="divXY">aaa</div>
 <div>
 <canvas id="canvas" width="400" height="300">
 This text is displayed if your browser does not support HTML5 Canvas.
 </canvas>
 </div>
 <script type="text/javascript">
 var canvas;
 var ctx;
 var x = 75;
 var y = 50;
 var WIDTH = 400;
 var HEIGHT = 300;
 var dragok = false;

function rect(x,y,w,h)
{
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
 function clear() {

 ctx.clearRect(0, 0, WIDTH, HEIGHT);

 }
 function init() {
 canvas = document.getElementById("canvas");
 ctx = canvas.getContext("2d");
  return setInterval(draw, 10);
 }

 function draw() {
 clear();
 ctx.fillStyle = "#FAF7F8";
 rect(0,0,WIDTH,HEIGHT);
 ctx.fillStyle = "#444444";
 rect(x - 15, y - 15, 30, 30);
}
function myMove(e){
 if (dragok){
 x = e.pageX - canvas.offsetLeft;
 y = e.pageY - canvas.offsetTop;
 document.getElementById("divXY").innerHTML = "x: " + x + " y: " + y;  
  }
 }

function myDown(e){ 
 if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
 canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
 e.pageY > y -15 + canvas.offsetTop){
 x = e.pageX - canvas.offsetLeft;
 y = e.pageY - canvas.offsetTop;
 dragok = true;
 canvas.onmousemove = myMove;
 document.getElementById("divXY").innerHTML = "x: " + x + " y: " + y;  

 } 

}

function myUp(){
 dragok = false;
 canvas.onmousemove = null;

}

    init();
   canvas.onmousedown = myDown;
   canvas.onmouseup = myUp;
  </script>
  </body

1 个答案:

答案 0 :(得分:1)

最后我得到了答案..我发布的代码在浏览器和移动应用程序中都有效。 你会从谷歌获得(jquery.ui.touch-punch.min.js)。

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1">


<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

<script src="http://code.jquery.com/ui/1.8.21/jquery-ui.min.js"></script>

 <script src="http://192.168.1.39/dragimage/www/jquery.ui.touch-punch.min.js"></script>

 <script>

 $(function() {


  $('#canvas1').draggable({cursor: 'move', containment: '#canvas', stop: function() {

        var cont = $('#canvas').offset();

        var img = $(this).offset();

        $('#xy').text('x-axis :' + (img.left - cont.left) + ', y-axis :' + (img.top -           cont.top));

     }});

   });


</script>

<style>

#canvas {

border:1px solid red;
}
</style>

</head>

<body>

 <div id="canvas" style="overflow: hidden; height:300px; width:300px;"> 

 <img id='canvas1' src='circle.png' name='image' >

 </div>

<div id='xy'></div>

</body>

</html>