Search code examples
javascriptkineticjs

Moving an image using touchmove in KineticJS


I want to move the image using 'touchmove' event,I know i can set dragging to true and use that but in need to use the 'touchmove' so that i can add more thing later (Zoom,Rotate,etc.).

The problem is :- 1- It's not responsive, it just randomly appear after few tries. 2- When the image is more than 50x50 nothing happens at all.

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<style>
  body {
    margin: 0px;
    padding: 0px;
  }
</style>
</head>
<body onmousedown="return false;">
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.2.min.js" >    </script>
<script defer="defer">
  var stage = new Kinetic.Stage({
    container: 'container',
    width: 250,
    height: 400
  });
  var layer = new Kinetic.Layer();
  function writeMessage(message) {
    text.setText(message);
    layer.draw();
  }

  var text = new Kinetic.Text({
    x: 10,
    y: 10,
    fontFamily: 'Calibri',
    fontSize: 24,
    text: '',
    fill: 'black'
  });       

  image=new Image();
  image.onload=function(){
  var map = new Kinetic.Image({
      x: 0,
      y: 0,
      image: image,
      width: 50,
      height: 50
  });

  map.on('touchstart',function() {
    writeMessage('Touchstart');
  });

  map.on('touchmove',function() {
    var touchPos = stage.getPointerPosition();
    var x = touchPos.x;
    var y = touchPos.y;
    var pos= {x:x,y:y};
    map.move(pos);
    writeMessage('x: ' + x + ', y: ' + y);
  });

  layer.add(map);
  stage.add(layer);

  };
  image.src='img/map-04.png';

  layer.add(text);   
</script>
</body>
</html>

Thanks in advance.


Solution

  • If you are using move function you have to pass dx and dy, nor absolute position. In your case you may use this:

    map.on('touchmove', function() {
      var pos = stage.getPointerPosition();
      map.position(pos);
      writeMessage('x: ' + pos.x + ', y: ' + pos.y);
    });