I am embarking on a journey to learn Javascript!
Can someone guide me on how to link a variable to the current xy coordinates in order to utilize relative positions for drawing lines? My goal is to create an etch-a-sketch using keyboard inputs - specifically the up, down, left, and right arrow keys - with a combination of JS, CSS, and HTML.
Appreciate any assistance!
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);
// specific drawing logic for left arrow key 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);
// specific drawing logic for up arrow key 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);
// specific drawing logic for right arrow key goes here
}
else {
}
}
if (key == 40) {
// down arrow
if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
etchContext.beginPath();
etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
// specific drawing logic for down arrow key goes here
}
else {
}
}
}
function clearCanvas() {
var etchMain = document.getElementById('etchMain');
var etchContext = etchMain.getContext('2d');
etchContext.clearRect(0, 0, etchMain.width, etchMain.height);
}