Jessie.J Jessie.J - 2 months ago 4
CSS Question

How to move an object using arrow keys using javascript

I want to be able to move a rectangle (that I created using javascript) around using the arrow keys. Also I want it to stop when hitting the end of my canvas. How do I do that? I'm all new at this and have absolutely no clue.



function fillRect () {

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var rectX=10;
var rectY=10;

context.rect(rectX,rectY,50,50);
context.fillStyle = "#666666";
context.fill();
}

function onkeydown(e) {
if(e.keyCode==39) {rectX++;} //right arrow
elseif(e.keyCode==37) {rectX--;} //left arrow
elseif(e.keyCode==38) {rectY--;} //up arrow
elseif(e.keyCode==40) {rectY++;} //down arrow
fillRect();
}
window.addEventListener("keydown", onkeydown);

#myCanvas {
margin: auto;
display: block;
width: 80%;
height: 400px;
background-color: white;
border: 3px solid black;
}

<!-- Jessica Odefjord -->
<!DOCTYPE HTML>
<html lang="sv">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="inlämningsuppgift_javascript_jessicaodefjord.css" />
<script type="text/javascript" src="inlämningsuppgift_javascript_jessicaodefjord.js"></script>
<title>Flytta rektangeln</title>
</head>
<body>
<header>
<h1>Flytta rektangeln</h1>
<h2>Flytta runt rektangeln med hjälp av piltangenterna</h2>
</header>
<main>
<section id="firstsection">
<h3>
</h3>
</section>
<canvas id="myCanvas">
</canvas>
</main>
</body>
</html>




Answer

Going through with the code gdros and yourself provided:

Fiddle: https://jsfiddle.net/k3akqz3c/1/

// Basic variables
var canvas;
var context;
var rectX = 10;
var rectY = 10;

// Set canvas context
window.onload = function() {
    canvas = document.getElementById("myCanvas");
    context = canvas.getContext("2d");
}

function fillRect() {
    context.beginPath();
    context.fillStyle = "#ffffff";
    context.fillRect(0, 0, 1000 + canvas.width, 1000 + canvas.height);
    context.beginPath();
    context.fillStyle = "#666666";

    // Check if the rect isn't out of bounds, if so: place it back.
    if (rectX < 0) {
        rectX = 0;
    } else if (rectX > 250) {
        rectX = 250;
    }
    if (rectY < 0) {
        rectY = 0;
    } else if (rectX > 100) {
        rectX = 100;
    }

    context.fillRect(rectX, rectY, 50, 50);
}

function onkeydown(e) {
    if (e.keyCode == 39) {
        rectX++;
    } //right arrow
    else if (e.keyCode == 37) {
        rectX--;
    } //left arrow
    else if (e.keyCode == 38) {
        rectY--;
    } //up arrow
    else if (e.keyCode == 40) {
        rectY++;
    } //down arrow
    fillRect();
}
window.addEventListener("keydown", onkeydown);

Essentially, you're recreating the rectangle every time you press one of the arrow keys, on a different position.

Comments