2017-10-04 83 views
1

我是JavaScript新用户!JS帆布:lineTo()

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

回答

0

我实施了一个真正的基本概念,你说什么只是因为它听起来很有趣。点击运行代码,然后点击画布框给出该框架焦点。事件处理程序将阻止窗口滚动,而是使用箭头输入来递增或递减xy并从那里绘制或者您可以点击空格键清除画布!

你失踪设计的位被存储Xÿ事件处理程序的外部,并使用的Xÿ以前的状态之间的差异来绘制你的画布线:

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