当元素更新位置时,为什么touchmove会被中断?

时间:2018-04-04 09:19:03

标签: javascript

我有基于mousemove事件中鼠标位置更新的svg元素。我尝试通过将touchmove绑定到元素来做同样的事情,但是当移动元素时,touchmove停止工作,元素在完全停止事件之前只是略微断断续续。有没有办法阻止touchmove在元素更新位置时取消?

$('svgCanvas').mousedown(function(e){
    // here I get element mouse is over
}

$('svgCanvas').mousemove(function(e){
    // here I update the position of the element based on e.pageX, e.pageY
    // the elements are saved in an array which updates as it moves
    Update();
}

//The function I'm trying to make work:
$('svgCanvas').bind('touchmove', function(e){
    e.preventDefault();
    var x = e.originalEvent.touches[0].pageX;
    var y = e.originalEvent.touches[0].pageY;
    if(elem){
       // elem is the element I get from mousedown (which also work on touch)
       elem.position[x,y];
    }
Update();
}

现在Update()做的是它从我拥有的元素数组中重绘屏幕上的所有svg元素。我很确定这就是问题所在,因为触摸事件一旦运行就会停止工作。然而,mousemove事件可以正常使用。

编辑:添加了该问题的摘要。



$(document).ready(function() {
  // Initialize variables
  var draw = SVG.get('svgCanvas'),
    group = draw.group().id('svgGroup'),
    clicking = false,
    data = [],
    newSvgElement = {},
    color = "#6658A4",
    elem;

  // Create a new svg element on click
  $('#image').click(function(e){
    var x = e.pageX;
    var y = e.pageY;
    var rand = Math.floor(Math.random() * 100000000);

    if(document.getElementById('createElement').checked){
      //Add the svg to an array as an Object
      newSvgElement.size = 30;
      newSvgElement.id = 'svgElement' + rand;
      newSvgElement.position = [x,y];
      data.push( Object.assign({}, newSvgElement) );
    }
    // Redraws all svg objects in the data[] array
    Update();
  });

  // Stop dragging the svg
  $("#svgCanvas").mouseup(function(){
    clicking = false;
  });

  // Drag the svg on mouse
  $("#svgCanvas").mousemove(function(e){
    if(clicking && document.getElementById("moveElement").checked){
      var x = e.pageX, y = e.pageY;

      if(elem){
        elem.position = [x,y];
        Update();
      }
    }
  });
  
  // Drag svg on touch, this is the one I have issues with
  $('#svgCanvas').bind('touchmove', function(e){
    if(document.getElementById("moveElement").checked) {
      var x = e.originalEvent.touches[0].pageX;
      var y = e.originalEvent.touches[0].pageY;
      
      if(elem){
        elem.position = [x,y];
        Update();
      }
    }
  });

  // Get the svg clicked, if its the background we dont want to move anything
  $("#svgCanvas").mousedown(function(e){
    if(document.getElementById("moveElement").checked) {
      var x = e.clientX,
        y = e.clientY,
        elementMouseIsOver = document.elementFromPoint(x, y).id;
      clicking = true;
      elem = dataInPosition(elementMouseIsOver);
    }
  });

  // Redraws every svg in the array
  function Update(){
    $("#svgGroup").empty();

    for (var i = 0; i < data.length; i++) {
      DrawPoint(data[i]);
    }
  }
  
  // Get the id of the clicked svg
  function dataInPosition(id) {
    if(data.length){
      var pos = data.map(function (element) {
        return element.id
      }).indexOf(id);
      return data[pos];
    }
  }

  // Creates the svg element using SVG.js
  function DrawPoint(svgObject){
    var size    = svgObject.size;
    var x       = svgObject.position[0];
    var y       = svgObject.position[1];

    var drawObject = group.circle(size).id(svgObject.id);
    drawObject.attr({
      fill: color,
      'fill-opacity': "0.0",
      stroke: color,
      'stroke-width': size/10,
      cx: x,
      cy: y
    });
  }
});
&#13;
#form{
  position: absolute;
  left: 30px;
  top: 30px;
}
&#13;
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.4/svg.js"></script>
<svg id="svgCanvas" height="900px" width="450px">
  <image id='image' xlink:href="http://routegadget.jukola.com/kartat/41.jpg" x="0" y="0" height="900px" width="450px"/>
</svg>
<div id="form">
  <form>
    <input type="radio" name="state" id="createElement" class="state" checked>
    <label for="createElement">Create Element <br/></label>
    <input type="radio" name="state" id="moveElement" class="state">
    <label for="moveElement">Move Element <br/></label>
  </form>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

所以你的小部件是“疯狂的”:)我的意思是它做了很多低效率的事情。 我把它改写成了我会写它的东西。

请检查出来。如果您需要澄清,请告诉我

至于我的想法:

  • 问题出在更新功能
  • 如果你注释掉第一个动作,那么group.clear()将删除所有绘制的圆圈,touchmove将开始在整个地方产生圆圈......但它会有点工作
  • 我怀疑svg.js做了一些让touchmove听众沉默的事情 因此我不会依赖这个图书馆
  • 但总的来说当前的方法效率非常低:在每个移动事件上重绘整个场景。这里有很多dom操纵。一旦你有很多圈子 - 即使你只需要移动一圈 - 你就会重新渲染一切。

我的代码也不完美,你仍然可以进一步优化它,但它目前的表现应该是好的。

// Initialize variables

// mode: on/off
var createMode = true;
// caching DOM stuff:
var svgCanvas = document.getElementById('svgCanvas');
var svgGroupContainer = document.getElementById('svgGroupContainer');
// this will hold our target element:
var elem;

// init method:
function onSVGinit() {
  // this will hold SVG space coordinates:
  var inputCoordinates = svgCanvas.createSVGPoint();
  // adding initial event listeners:
  svgCanvas.addEventListener('mousedown', mouseDown, { passive: true })
  svgCanvas.addEventListener('touchstart', touchDown, { passive: true })
  // on input methods:
  function mouseDown(e) {
    elem = e.target;
    // need to do coordinates conversion to match SVG space:
    inputCoordinates.x = event.clientX;
    inputCoordinates.y = event.clientY;
    inputCoordinates = inputCoordinates.matrixTransform(svgCanvas.getScreenCTM().inverse());
    svgCanvas.addEventListener('mousemove', move, { passive: true })
    svgCanvas.addEventListener('mouseup', end, {passive:true});
  }
  function touchDown(e) {
    elem = e.target
    // need to do coordinates conversion to match SVG space:
    inputCoordinates.x = event.touches[0].clientX;
    inputCoordinates.y = event.touches[0].clientY;
    inputCoordinates = inputCoordinates.matrixTransform(svgCanvas.getScreenCTM().inverse());
    svgCanvas.addEventListener('touchmove', move, { passive: true })
    svgCanvas.addEventListener('touchup', end, {passive:true});
  }
  function move(e) {
    if (!createMode) {
    // need to do coordinates conversion to match SVG space:
    inputCoordinates.x = event.clientX? event.clientX : event.touches[0].clientX;
    inputCoordinates.y = event.clientY? event.clientY : event.touches[0].clientY;
    inputCoordinates = inputCoordinates.matrixTransform(svgCanvas.getScreenCTM().inverse());
    }
    elem.setAttribute("cx", inputCoordinates.x);
    elem.setAttribute("cy", inputCoordinates.y);
  }
  function end(e) {
    // dynamically remove listeners:
    svgCanvas.removeEventListener('touchmove', move, { passive: true });
    svgCanvas.removeEventListener('mousemove', move, { passive: true });
    svgCanvas.removeEventListener('touchup', move, { passive: true });
    svgCanvas.removeEventListener('mouseup', move, { passive: true });
    // if createMode is on - we spawn a circle:
    if (createMode) {
       createCircle()
    }
  }
  // function to create circle element:
  function createCircle() {
    var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle")
    circle.setAttribute("cx", inputCoordinates.x);
    circle.setAttribute("cy", inputCoordinates.y);
    circle.setAttribute("r", 30);
    circle.setAttribute("fill", "transparent");
    circle.setAttribute("stroke","#6658A4")
    svgGroupContainer.appendChild(circle);
  } 
};
function switchMode(e) {
    createMode = !createMode;
}
#form{
  position: absolute;
  left: 30px;
  top: 30px;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.4/svg.js"></script>
<svg id="svgCanvas" height="900px" width="450px" onload="onSVGinit()">
  <image id='image' xlink:href="http://routegadget.jukola.com/kartat/41.jpg" x="0" y="0" height="900px" width="450px"/>
  <g id="svgGroupContainer"></g>
</svg>
<div id="form">
  <form>
    <input type="radio" name="state" id="createElement" class="state" onclick="switchMode()" checked>
    <label for="createElement">Create Element <br/></label>
    <input type="radio" name="state" id="moveElement" class="state" onclick="switchMode()">
    <label for="moveElement">Move Element <br/></label>
  </form>
</div>