2017-10-04 79 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" />