JS Canvas:lineTo()

时间:2017-10-04 22:58:45

标签: javascript css

我是Javascript的新手!

如何将变量赋值给当前的xy坐标,这样我可以使用相对位置来绘制线条?尝试用键盘蚀刻草图。上,下,左,右箭头键......使用JS,CSS和HTML。

谢谢!

window.addEventListener("keydown", keyd);
function keyd(event) {
  var etchMain = document.getElementById('etchMain');
  var etchContext = etchMain.getContext('2d');
  var key = event.keyCode;
  **var etchContextPositionX;
  var etchContextPositionY;**
  if (key == 37) {
    // left arrow
    if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
      etchContext.beginPath();
      etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
      // arrow specific drawing goes here
    }
    else {

    }
  }
  if (key == 38) {
    // up arrow
    if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
      etchContext.beginPath();
      etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
      // arrow specific drawing goes here
    }
    else {

    }
  }
  if (key == 39) {
    // right arrow
    if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
      etchContext.beginPath();
      etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
      // arrow specific drawing goes here
    }
    else {

    }
  }
  if (key == 39) {
    // down arrow
    if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
      etchContext.beginPath();
      etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
      // arrow specific drawing goes here

    }
    else {

    }
  }
}
function clearCanvas() {
  var etchMain = document.getElementById('etchMain');
  var etchContext = etchMain.getContext('2d');
  etchContext.clearRect(0, 0, etchMain.width, etchMain.height);
}

1 个答案:

答案 0 :(得分:0)

我实现了一个非常基本的想法,只是因为它听起来很有趣。点击 run snippet ,然后点击画布框以获得该帧焦点。事件处理程序将阻止窗口滚动,而是使用箭头输入来递增或递减 x y 并从那里绘制,或者您可以按空格键清除画布! / p>

您缺少的设计是将 x y 存储在事件处理程序之外,并使用 x 和 y 绘制画布线:



var pos = {
  x: 50,
  y: 50,
}

var etchMain = document.getElementById('etchMain');
var etchContext = etchMain.getContext('2d');

window.addEventListener('keydown', function(e) {
  e.preventDefault();
  
  if(e.keyCode === 32) {
    clearCanvas();
  } else {

    etchContext.beginPath();
    etchContext.moveTo(pos.x, pos.y);

    switch (e.keyCode) {
      //left arrow
      case 37:
        pos.x--;
        break;
      //up arrow
      case 38:
        pos.y--;
        break;
      //right arrow
      case 39:
        pos.x++;
        break;
      //down arrow
      case 40:
        pos.y++;
        break;
      default:
        break;
      }

      etchContext.lineTo(pos.x, pos.y);
      etchContext.stroke();
    }
});

function clearCanvas() {
  etchContext.clearRect(0, 0, etchMain.width, etchMain.height);
}

#etchMain {
  border: 1px solid black;
}

<canvas id="etchMain" height="100" width="100" />
&#13;
&#13;
&#13;