проблемы с HTML Canvas - PullRequest
       63

проблемы с HTML Canvas

2 голосов
/ 03 августа 2020

Я просто использовал несколько кодов для создания холста (HTML и JavaScript), на котором мои клиенты могут писать свои подписи с компьютера (с помощью мыши) или мобильного телефона (касанием пальца). После запуска этих кодов я обнаружил 2 проблемы.

  • Первая проблема заключается в том, что мышь не может нарисовать линию (просто показывала точку в начале каждой строки, которую я хотел нарисовать ).

  • Вторая проблема заключается в том, что когда я использовал палец для рисования линии на сотовом телефоне, положение линии не там, где я хочу, чтобы она отображалась. Может ли кто-нибудь помочь мне взглянуть на эти 2 проблемы? Большое спасибо!

var canvas, ctx, flag, dot_flag = false,
  prevX = 0,
  currX = 0,
  prevY = 0,
  currY = 0,

  lastPt = null,

  x = "black",
  y = 2;


function init() {
  canvas = document.getElementById('can');
  ctx = canvas.getContext("2d");
  w = canvas.width;
  h = canvas.height;

  canvas.addEventListener("mousemove", function(e) {
    findxy('move', e)
  }, false);
  canvas.addEventListener("mousedown", function(e) {
    findxy('down', e)
  }, false);
  canvas.addEventListener("mouseup", function(e) {
    findxy('up', e)
  }, false);
  canvas.addEventListener("mouseout", function(e) {
    findxy('out', e)
  }, false);


  canvas.addEventListener("touchmove", draw, false);
  canvas.addEventListener("touchend", end, false);

}



function draw() {
  ctx.beginPath();
  ctx.moveTo(prevX, prevY);
  ctx.lineTo(currX, currY);
  ctx.strokeStyle = x;
  ctx.lineWidth = y;
  ctx.stroke();
  ctx.closePath();
}


function draw(e) {
  e.preventDefault();
  if (lastPt != null) {
    ctx.beginPath();
    ctx.moveTo(lastPt.x, lastPt.y);
    ctx.lineTo(e.touches[0].pageX, e.touches[0].pageY);
    ctx.stroke();
  }
  lastPt = {
    x: e.touches[0].pageX,
    y: e.touches[0].pageY
  };
}

function end(e) {
  e.preventDefault();
  // Terminate touch path
  lastPt = null;
}



function erase() {

  ctx.clearRect(0, 0, w, h);
  document.getElementById("canvasimg").style.display = "none";

}

function save() {
  document.getElementById("canvasimg").style.border = "2px solid";
  var dataURL = canvas.toDataURL();
  document.getElementById("canvasimg").src = dataURL;
  document.getElementById("canvasimg").style.display = "inline";
  document.getElementById("can").style.display = "none";

}

function findxy(res, e) {
  if (res == 'down') {
    prevX = currX;
    prevY = currY;
    currX = e.clientX - canvas.offsetLeft;
    currY = e.clientY - canvas.offsetTop;

    flag = true;
    dot_flag = true;
    if (dot_flag) {
      ctx.beginPath();
      ctx.fillStyle = x;
      ctx.fillRect(currX, currY, 2, 2);
      ctx.closePath();
      dot_flag = false;
    }
  }
  if (res == 'up' || res == "out") {
    flag = false;
  }
  if (res == 'move') {
    if (flag) {
      prevX = currX;
      prevY = currY;
      currX = e.clientX - canvas.offsetLeft;
      currY = e.clientY - canvas.offsetTop;
      draw();
    }
  }
}
<html>

<body onload="init()">
  <canvas id="can" width="400" height="400" style="border-style: solid; border-color: inherit; border-width: 2px; position:absolute;top:9%; left:12%;"></canvas>

  <img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">
  <input type="button" value="确认" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">
  <input type="button" value="清除" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">
</body>

</html>
...