Talk the guys! I am a beginner in JS and HTML. There is a lot that I understand the reasoning but I fumble at the time of coding. I'll try to explain what I'm trying to do. I'm drawing a triangle (called Jack), with a little red nose (mini triangle) and an eye (circle), until good. My goal is to move Jack to directions according to the arrow keys, with his nose always pointing to the direction he is moving. Ah, and when you hit the reset button, it goes back to the initial position, which is the center of the canvas.
I tried to draw more or less the command, but it does not work. Below I will show my HTML and my JS. What am I missing in JS? I did not understand how to rotate the jack, would I have to rotate inside the switch of each key?
Thanks!
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas</title>
<script src="a5.js" type="text/javascript" defer></script>
</head>
<body onload="setUp()">
<h1>The Adventure of Jack the Triangle</h1>
<canvas id="myCanvas" height="500" width="500" style="border: 1px solid black"></canvas>
<br>
<button type="button" id="resetbtt" name="button">Reset</button>
</body>
JS:
let canvas;
let ctx;
let dx = 10;
let dy = 10;
let x = 250;
let y = 250;
function setUp(){
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
drawJack();
}
function drawJack(){
ctx.save();
ctx.translate(x,y)
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(-50, 50);
ctx.lineTo(50, 50);
ctx.closePath();
ctx.stroke();
ctx.restore();
//NARIZ
ctx.save();
ctx.fillStyle = "red";
ctx.translate(x,y)
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(-10, 10);
ctx.lineTo(10, 10);
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.restore();
//OLHO
ctx.save();
ctx.fillStyle = "blue";
ctx.translate(x,y)
ctx.beginPath();
ctx.arc(0, 30, 5, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
}
let deltaX = 0;
let deltaY = 0;
window.addEventListener("keydown", moveJack);
function moveJack(e) {
switch(e.keyCode) {
case 37:
x -= dx;
break;
case 38:
y -= dy;
break;
case 39:
x += dx;
break;
case 40:
y += dy;
break;
}
e.preventDefault();
}