Jessie.J Jessie.J - 1 month ago 10
CSS Question

How to stop an object when hitting the end of the canvas using JavaScript?

I'm having this rectangle that I've created using javascript, and I can move it with the arrow keys. So far so good. Now my problem is that I want it to stop when hitting the end of the canvas. I don't want it to be able to disappear outside of the canvas. How do I do that?

Here's my code:

var canvas;
var context;
var rectX=10;
var rectY=10;

function fillRect() {
context.fillStyle = "#ffffff";

context.fillStyle = "#666666";

function onkeydown(e) {
if(e.keyCode==39) {rectX++;} //höger pil
else if(e.keyCode==37) {rectX--;} //vänster pil
else if(e.keyCode==38) {rectY--;} //uppåt pil
else if(e.keyCode==40) {rectY++;} //nedåt pil

window.addEventListener("keydown", onkeydown);

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


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

<!-- Jessica Odefjord -->
<html lang="sv">
<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_2.js"></script>
<title>Flytta rektangeln</title>
<h1>Flytta rektangeln</h1>
<h2>Flytta runt rektangeln med hjälp av piltangenterna</h2>
<section id="firstsection">
<canvas id="myCanvas">


This is probably not the most efficient way to do it, but you could check in onkeydown if the movement will or will not send your rectangle away, and then move it only if it is safe.

EDIT : Something like this should do the trick :)

function onkeydown(e) {
    if(e.keyCode==39 && rectX+50 < canvas.width) {rectX++;} //höger pil
    else if(e.keyCode==37 && rectX > 0) {rectX--;} //vänster pil
    else if(e.keyCode==38 && rectY > 0) {rectY--;} //uppåt pil
    else if(e.keyCode==40 && rectY+50 < canvas.height) {rectY++;} //nedåt pil