I am attempting to create a basic canvas box that moves using arrow keys. Here is the code:
Here's the code snippet:
$(function() {
var n = 3;
var xD = 0;
var yD = 0;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ss = {
"x": 0,
"y": 0,
"width": 100,
"height": 75
};
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(ss.x, ss.y, ss.width, ss.height);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
ctx.stroke();
}
function move() {
x = ss.x + (xD * n);
y = ss.y + (yD * n);
ss.x = x;
ss.y = y;
}
$(document).keydown(function(e) {
xD = e.which == 37 ? -1 : xD;
xD = e.which == 39 ? 1 : xD;
yD = e.which == 38 ? -1 : yD;
yD = e.which == 40 ? 1 : yD;
e.preventDefault();
});
$(document).keyup(function(e) {
xD = e.which == 37 ? 0 : xD;
xD = e.which == 39 ? 0 : xD;
yD = e.which == 38 ? 0 : yD;
yD = e.which == 40 ? 0 : yD;
e.preventDefault();
});
render();
setInterval(move, .01);
});
body {
margin: 0;
}
#canvas {
border: 1px solid #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>
This script should enable the following functionalities:
- Moving the box by pressing arrow keys
- Adjusting canvas dimensions to
width = "100vw"
andheight = "100vh"