繁体   English   中英

JS画布:lineTo()

[英]JS Canvas: lineTo()

我是Java新手!

如何为当前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);
}

我实施了一个真正基本的想法,只是听起来很有趣。 点击run snippet ,然后单击画布框以使该框架聚焦。 事件处理程序将防止窗口滚动,而是使用箭头输入来递增或递减xy并从那里进行绘制,或者您可以按空格键清除画布!

您缺少的设计点是将xy存储在事件处理程序之外,并使用xy的先前状态之间的差异来绘制画布线:

 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" /> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM