与javascript中的两个函数冲突,用于画布绘制

时间:2016-12-17 19:20:30

标签: javascript jquery

有两种不同的功能用于在画布上绘制自由绘图和线条图。但是当一个函数被调用时,其他函数无法正常工作。如果首先调用线条绘制函数,并且当我们按下按钮以绘制自由时,它也会绘制线条。在相反的情况下,绘制连续线。下面给出两个函数。 免费绘图

function free(){
  var canvas=document.getElementById('canvas');
  var radius=10;
  var dragging1=false;


  context.lineWidth=2*radius;

  var putPoint=function(e) {
  if(dragging1){
  context.lineTo(e.clientX,e.clientY);
  context.stroke();
  context.beginPath();
  context.arc(e.clientX,e.clientY,radius,0,Math.PI*2);
  context.fill();
  context.beginPath();
  context.moveTo(e.clientX,e.clientY);
  }//end of if
}

var engage = function(e) {
  dragging1=true;
  putPoint(e);
}

var disengage = function() {
  dragging1=false;
  context.beginPath();
}
canvas.addEventListener('mousedown',engage);
canvas.addEventListener('mousemove',putPoint);
canvas.addEventListener('mouseup',disengage);
}

对于线路助行     function line(){     var canvas,         背景下,         dragging = false,         dragStartLocation,         快照;

function getCanvasCoordinates(event) {
  var x = event.clientX - canvas.getBoundingClientRect().left,
      y = event.clientY - canvas.getBoundingClientRect().top;

  return {x: x, y: y};
}

function takeSnapshot() {
  snapshot = context.getImageData(0, 0, canvas.width, canvas.height);
}

function restoreSnapshot() {
  context.putImageData(snapshot, 0, 0);
}


function drawLine(position) {
  context.beginPath();
  context.moveTo(dragStartLocation.x, dragStartLocation.y);
  context.lineTo(position.x, position.y);
  context.stroke();
}

function dragStart(event) {
  dragging = true;
  dragStartLocation = getCanvasCoordinates(event);
  takeSnapshot();
}

function drag(event) {
  var position;
    if (dragging === true) {
      restoreSnapshot();
      position = getCanvasCoordinates(event);
      drawLine(position);
    }
}

function dragStop(event) {
  dragging = false;
  restoreSnapshot();
  var position = getCanvasCoordinates(event);
  drawLine(position);
}

function init() {
  canvas = document.getElementById("canvas");
  context = canvas.getContext('2d');
  context.strokeStyle = 'purple';
  context.lineWidth = 6;
  context.lineCap = 'round';

  canvas.addEventListener('mousedown', dragStart, false);
  canvas.addEventListener('mousemove', drag, false);
  canvas.addEventListener('mouseup', dragStop, false);
}
init()
}

我该如何解决这个问题? Iam坚持这一点。

1 个答案:

答案 0 :(得分:1)

在这种情况下,请创建两个函数来删除另一个函数中的事件侦听器。这意味着创建功能

    function removeLineListeners(){
      canvas.removeEventListener('mousedown', dragStart);
      canvas.removeEventListener('mousemove', drag);
      canvas.removeEventListener('mouseup', dragStop);
    }

    function removeFreeListeners(){
      canvas.removeEventListener('mousedown',engage,false);
      canvas.removeEventListener('mousemove',putPoint,false);
      canvas.removeEventListener('mouseup',disengage,false);
    }

所以在什么时候添加removeLineListeners()到free的开始和 removeFreeListeners()到strting的Line函数。这对我有用